PHP Operators

Operators perform operations on the variables. Operators are symbols that tell the PHP compiler to perform specific actions. In this unit, we study how to perform the operations on the variables using operators in PHP.

Read Also: PHP Constants

Operators in PHP

Operators are the symbol that tells the processor to perform some actions. For example, the operator (+) tells PHP to add two variables. PHP operators perform operations on variables or values. An operator takes values, which are known as operands and perform operations on them and gives a result. PHP borrows most of its operators from Perl and C. Just like various other programming languages, PHP also supports multiple operators.

The following are the most common operators used in PHP.

  • Arithmetic Operators
  • Logical or relational operators
  • Comparison Operators
  • Conditional or ternary Operators
  • Assignment Operators
  • Spaceship Operators
  • Array Operators
  • Increment/Decrement Operators
  • String Operators

We can also categorize the operators on behalf of operands. They categorize in 3 forms.

  1. Unary Operators: Works on single operand such as ++, — etc.
  2. Binary Operators: Works on two operands such as +,-,*, etc.
  3. Ternary operators: Works on three operands such as “?:”.

A detail Description about each of these Operators:

Arithmetic Operators 

The arithmetic operators require numeric values, and non-numeric values are converted automatically to numeric values. It Performs simple mathematical operations such as addition, Subtraction, etc.

OperatorNameExampleDescription
+Addition$a + $bSum of $a & $b
Subtraction$a – $bDifference of $a & $b
*Multiplication$a * $bProduct of $a & $b
/Division$a / $bQuotient of $a & $b
%Modulus$a % $bRemainder of $a divided by $b
**Exponentiation$a ** $b$a raised to the power $y

Example

<?php 

$a=20;

$b=10;

echo ($a+$b), “\n”;

echo($a-$b), “\n”;

echo ($a*$b), “\n”;

echo ($a/$b), “\n”;

echo (a % b), “\n”;

?>

Output

30

10

200

2

5

Logical or Relational Operators

Logical Operators help to build the logical expressions. They operate with conditional statements. Condition can either be met or not, so the result of the conditional statement can be either true or false.

OperatorNameExampleDescription
AndAND$a and $bIt returns a value of TRUE if both its operands are true.
OrOR$a or $bIt returns a value of true if either of its operands is true.
xorXOR$a xor $bTrue if either $x or $z is real but not both
&&AND$a && $bIt returns a value of TRUE if both its operand is right.
|| OR$a || $bIt returns a value of true if either of its operands is true.
!NOT!$aIt returns a value of true when $a is not true.

Example

<?php 

$a = 50; 

$b = 30; 

if ($a == 50 and $b == 30) 

    echo "and Success \n"; 

if ($a == 50 or $b == 20) 

    echo "or Success \n"; 

if ($a == 50 xor $b == 20) 

    echo "xor Success \n"; 

if ($a == 50 && $b == 30) 

    echo "&& Success \n"; 

if ($a == 50 || $b == 20) 

    echo "|| Success \n"; 

  if (!$c) 

    echo "! Success \n"; 

 ?>

Output

and Success

or Success

xor Success

&& Success

|| Success

! Success

Comparison Operators

PHP Provides comparison operator to compare to two operands. It returns, either true or false. If the comparison is correct; it returns true. Otherwise, it returns false.

OperatorNameExampleDescription
==Equal$a == $bIt returns a value of true if $a is equal to $b
===Identical$a === $bIt returns a value of true if $a is equal to $b, and both are of the same type.
!=Not equal$a != $bIt returns a value of true if $a is not equal to $b
<>Not equal$a <> $bIt returns a value of true if $a is not equal to $b
! ==Not identical$a !== $bIt returns a value of true if $a is not equal to $b and both are not of same type
<Less than$a < $bIt returns a value of true if $a is greater than $b
>Greater than$a > $bIt returns a value of true if $a is less than $b
>=Greater than or equal to$a >= $bIt returns a value of true if $a is greater than or equal to $b
<=Less than or equal to$a <= $bIt returns a value of true if $a is less than or equal to $b

Example

<?php

$a = 80; 

$b = 50; 

$c = "80"; 

var_dump($a == $c) + "\n"; 

var_dump($a != $b) + "\n"; 

var_dump($a <> $b) + "\n"; 

var_dump($a === $c) + "\n"; 

var_dump($a !== $c) + "\n"; 

var_dump($a < $b) + "\n"; 

var_dump($a > $b) + "\n"; 

var_dump($a <= $b) + "\n"; 

var_dump($a >= $b); 

?> 

Output

bool(true)

bool(true)

bool(true)

bool(false)

bool(true)

bool(false)

bool(true)

bool(false)

Conditional or Ternary Operators

This operator first evaluates an expression true or false and then execute one of the two given statements depending upon the result of the evaluation.

Syntax

$var = (condition)? value1 : value2;

Here condition will either true or false. The value one will be assigned to $var if the condition evaluates to True, otherwise value two assign to it.

OperatorNameDescription
?:Ternary If the condition is true? Then $x: or else $y. It means if the condition is true, then left the result of the colon is accepted, otherwise the result on the right.

 

Example

<?php 

$a = -12; 

echo (ax > 0) ? 'The number is positive' : 'The number is negative'; 

?>

Output

The number is negative.

Assignment Operator

It assigns a value to the variables. Operand on the left side is always a variable, and the operand on the right side can be a literal value, variable, expression, or function call that returns a value.

OperatorNameExampleDescription
=Assign$a = $bAssign the result
+=Add and assign$a += $bAdds two numbers and assign the result to the first
-=Subtract and assign$a -= $bSubtracts two numbers and assign the result to the first
*=Multiply and assign$a *= $bMultiply two numbers and assign the result to the first
/=Divide and assign quotient$a /= $bDivide two numbers and assign the result to the first
%=Divide and assign modulus$a %= $bComputes the modulus of two numbers and assign the result to the first

Example

<?php 

// simple assign operator 

$a = 75; 

echo $a, "\n"; 

// add then assign operator 

$a = 100; 

$a += 200; 

echo $a, "\n"; 

// subtract then assign operator 

$a = 70; 

$a -= 10; 

echo $a, "\n"; 

// multiply then assign operator 

$a = 30; 

$a *= 20; 

echo $a, "\n"; 

// Divide then assign(quotient) operator 

$a = 100; 

$a /= 5; 

echo $a, "\n"; 

// Divide then assign(remainder) operator 

$a = 50; 

$a %= 5; 

echo $a; 

?>

Output

75

300

60

600

20

0

Array Operator

The array operators and functions act on the entire array. We can perform operations on array using Array operators.

OperatorNameExampleDescription
+Union      $a + $bUnion of $a & $b
==Equality      $a == $bIt returns the value of true if $a & $b have the same key/value pair.
===Identity      $a === $bIt returns the value of true if $a & $b have the same key/value pair in the same order and of the same type
!=Inequality      $a != $bIt returns true value if $a is not equal to $b
<>Inequality       $a <> $bIt returns true value if $a is not equal to $b
!==Non-identity       $a! = $bIt returns true value if $a is not identical to $b

Example

<?php

$a = array("a" => "Red", "b" => "Green", "c" => "Blue");

$b = array("u" => "Yellow", "v" => "Orange", "w" => "Pink");

$c = $a + $b;

var_dump($c);

var_dump($a == $b);

var_dump($a === $b);

var_dump($a != $b);

var_dump($a <> $b);

var_dump($a !== $b);

?>

Output

boolean false 

boolean false

boolean true

boolean true

boolean true

Increment/Decrement Operators

Increment (++) and decrement (-) operators give you a quick way to increase and decrease the value of a variable by 1.

OperatorNameDescription
++$aPre incrementIncrements $a by one , then returns $a
$a++Post incrementReturn $a then increments $a by one
–$aPre decrementDecrements $a by one , then returns $a
$x–Post decrementReturn $a then decrements $a by one

Example

<?php 

$x = 2; 

echo ++$x, " First increments then prints \n"; 

echo $x, "\n"; 

$x = 2; 

echo $x++, " First prints then increments \n"; 

echo $x, "\n"; 

$x = 2; 

echo --$x, " First decrements then prints \n"; 

echo $x, "\n"; 

$x = 2; 

echo $x--, " First prints then decrements \n"; 

echo $x; 

?> 

Output

3 First increments then prints

3

2 First prints then increments

3

1 First decrements then prints

1

2 First prints then decrements

1

String Operators

There are two operators for strings. These operators can be executed over strings.

OperatorNameExampleDescription
.Concatenation     $str 1 . $str2Concates $str1 and $str2
  .=Concatenation Assignment      $str1 . = $str2Appends $str1 to the $str2

Example

<?php 

$x = "How"; 

$y = "are"; 

$z = "you!!!"; 

echo $x. $y. $z, "\n"; 

$x.= $y. $z; 

echo $x; 

?>

Output:

How are you!!!

How are you!!!

Spaceship Operator 

PHP 7 brought a new operator called spaceship operator (<=>). It Compares two expressions. It is also called a combined comparison operator. This operator is similar to strcmp(). This operator uses with integers , floats,strings,arrays,objects etc.

  • If values on either side are equal, it returns 0.
  • If the value on the left side is greater, it returns 1.
  • It returns -1 if the value on the right is greater.

Example

<?php 

$x = 50; 

$y = 50; 

$z = 25; 

echo $x <=> $y; 

echo "\n"; 

echo $x <=> $z; 

echo "\n"; 

echo $z <=> $y; 

echo "\n"; 

// We can do the same for Strings 

$x = "Suman"; 

$y = "Hello"; 

echo $x <=> $y; 

echo "\n"; 

echo $x <=> $y; 

echo "\n";

echo $y <=> $x; 

?> 

Output

0

1

-1

1

1

-1

Execution Operator

PHP has an execution operator backticks (“). PHP executes the content of backticks as a shell command. Execution operator and shell_exec() give the same result.

OperatorNameExampleDescription
Backticks      echo `dir`;Executes the shell command and returns the result.

 

In the example, it will show the directories available in the existing folder.

Error Control Operators

PHP has one error control operator, i.e., at (@) symbol. Whenever it uses an expression, any error message will be ignored that might be generated by that expression.

OperatorNameExampleDescription
@At@file (‘non-existent file’)           File Error

PHP Operators Precedence

The operator’s precedence decides which order the operator evaluates in an expression. Each operator is assigned a precedence. Some operators have equal precedence, e.g., the precedence of the add( +) and subtract( -) is equal. However, some operators have higher precedence than others, e.g., the precedence of the multiply operator ( *) is higher than the precedence of the add( +) and the subtract ( -) operators.

For example, x = 7 + 3 * 2; Here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

OperatorNameAssociativity
clone newClone and newNon-Associative
[ArrayLeft
**ArithmeticRight
++ — ~ (int) (float) (string) (array) (object) (bool) @Increment / decrement and typesRight
Instance ofTypesNon-associative
!logical (negation)Right
* / %ArithmeticLeft
+ – .arithmetic and string concatenationLeft
<< >>bitwise (shift)Left
< <= > >=Comparisonnon-associative
== != === !== <>Comparisonnon-associative
&bitwise ANDLeft
^bitwise XORLeft
|bitwise ORLeft
&&logical ANDLeft
||logical ORLeft
?:TernaryLeft
= += -= *= **= /= .= %= &= |= ^= <<= >>= =>AssignmentRight
AndLogicalLeft
XorLogicalLeft
OrLogicalLeft
,many uses (comma)Left

Read More: PHP Strings

Conclusion

Operators are used with variables for various actions or with functions for changing previously declared values.

Operators divides into seven groups based on their purpose: arithmetic, comparison, assignment, increment or decrement, string, logical, and array.

I hope you have a better understanding of PHP Operators.

Leave a Reply

Your email address will not be published. Required fields are marked *