PHP Operators


In this chapter, we will discuss the application of different operators in PHP.

In PHP, the assignment operator=is used to assign values to variables.

In PHP, the arithmetic operators+are used to add values together.


PHP Arithmetic Operators

Operator Name Description Example Result
x + y add Sum of x and y 2 + 2 4
x - y subtract Difference of x and y 5 - 2 3
x * y multiply Product of x and y 5 * 2 10
x / y divide Quotient of x and y 15 / 5 3
x % y Modulus (remainder of division) Remainder of x divided by y 5 % 2
10 % 8
10 % 2
1
2
0
-x Set negative Take the opposite sign of x
<?php
$x = 2;
echo -$x;
?>
-2
~x Bitwise not

Invert x, performing a bitwise NOT operation on its binary bits. The rules are:

~1=-2;   
~0=-1;
<?php
$x = 2;
echo ~$x;
?>
-3
a . b Concatenation Concatenate two strings "Hi" . "Ha" HiHa

The following examples demonstrate the different results obtained using different arithmetic operators:

Example

<?php $x=10; $y=6; echo ($x + $y); //Outputs 16 echo '<br>'; //Newline echo ($x - $y); //Outputs 4 echo '<br>'; //Newline echo ($x * $y); //Outputs 60 echo '<br>'; //Newline echo ($x / $y); //Outputs 1.6666666666667 echo '<br>'; //Newline echo ($x % $y); //Outputs 4 echo '<br>'; //Newline echo -$x; ?>

Try it yourself »

PHP7+ version adds an integer division operatorintdiv(), this function returns the value of the first parameter divided by the second parameter and rounds it down (floor). Example:

Example

<?php var_dump(intdiv(10, 3)); ?>

The above example will output:

int(3)

PHP Assignment Operators

In PHP, the basic assignment operator is=. It means that the left operand is set to the value of the right-hand side expression. That is,$x = 5the value is 5.

Operator Equivalent to Description
x = y x = y The left operand is set to the value of the right-hand side expression
x += y x = x + y add
x -= y x = x - y subtract
x *= y x = x * y multiply
x /= y x = x / y divide
x %= y x = x % y Modulus (remainder of division)
a .= b a = a . b Concatenate two strings

The following examples demonstrate the different results obtained using different assignment operators:

Example

<?php $x=10; echo $x; //Outputs 10 $y=20; $y += 100; echo $y; //Outputs 120 $z=50; $z -= 25; echo $z; //Outputs 25 $i=5; $i *= 6; echo $i; //Outputs 30 $j=10; $j /= 5; echo $j; //Outputs 2 $k=15; $k %= 4; echo $k; //Outputs 3 ?>

Try it yourself »

The following examples demonstrate the same results obtained using different string operators:

Example

<?php $a = "Hello"; $b = $a . " world!"; echo $b; //Outputs Hello world! $x="Hello"; $x .= " world!"; echo $x; //Outputs Hello world! ?>

Try it yourself »

PHP Increment/Decrement Operators

Operator Name Description
++ x Pre-increment Adds 1 to x, then returns x
x ++ Post-increment Returns x, then adds 1 to x
-- x Pre-decrement Subtracts 1 from x, then returns x
x -- Post-decrement Returns x, then subtracts 1 from x

The following examples demonstrate the results obtained using increment/decrement operators:

Example

<?php $x=10; echo ++$x; //Outputs 11 $y=10; echo $y++; //Outputs 10 $z=5; echo --$z; //Outputs 4 $i=5; echo $i--; //Outputs 5 ?>

Try it yourself »

PHP Comparison Operators

Comparison operators allow you to compare two values:

Operator Name Description Example
x == y Equal Returns true if x equals y 5==8 returns false
x === y Identical Returns true if x equals y and they are of the same type 5==="5" returns false
x != y Not equal Returns true if x does not equal y 5!=8 returns true
x <> y Not equal Returns true if x does not equal y 5<>8 returns true
x !== y Not identical Returns true if x does not equal y, or if they are not of the same type 5!=="5" returns true
x > y Greater than Returns true if x is greater than y 5>8 returns false
x < y Less than Returns true if x is less than y 5<8 returns true
x >= y Greater than or equal to Returns true if x is greater than or equal to y 5>=8 returns false
x <= y Less than or equal to Returns true if x is less than or equal to y 5<=8 returns true

The following examples demonstrate the different results obtained using some comparison operators:

Example

<?php $x=100; $y="100"; var_dump($x == $y); echo "<br>"; var_dump($x === $y); echo "<br>"; var_dump($x != $y); echo "<br>"; var_dump($x !== $y); echo "<br>"; $a=50; $b=90; var_dump($a > $b); echo "<br>"; var_dump($a < $b); ?>

Try it yourself »

PHP Logical Operators

Operator Name Description Example
x and y and Returns true if both x and y are true x=6
y=3
(x < 10 and y > 1) returns true
x or y or Returns true if at least one of x and y is true x=6
y=3
(x==6 or y==5) returns true
x xor y Xor Returns true if exactly one of x and y is true x=6
y=3
(x==6 xor y==3) returns false
x && y and Returns true if both x and y are true x=6
y=3
(x < 10 && y > 1) returns true
x || y or Returns true if at least one of x and y is true x=6
y=3
(x==5 || y==5) returns false
! x not Returns true if x is not true x=6
y=3
!(x==y) returns true

PHP Array Operators

Operator Name Description
x + y Union Union of x and y
x == y Equality Returns true if x and y have the same key/value pairs
x === y Identity Returns true if x and y have the same key/value pairs, in the same order and of the same type
x != y Inequality Returns true if x is not equal to y
x <> y Inequality Returns true if x is not equal to y
x !== y Non-identity Returns true if x is not equal to y

The following examples demonstrate the different results obtained using some array operators:

Example

<?php $x = array("a" => "red", "b" => "green"); $y = array("c" => "blue", "d" => "yellow"); $z = $x + $y; //Union of $x and $y arrays var_dump($z); var_dump($x == $y); var_dump($x === $y); var_dump($x != $y); var_dump($x <> $y); var_dump($x !== $y); ?>

Try it yourself »

Ternary Operator

Another conditional operator is the "?:" (or ternary) operator.

Syntax format

(expr1) ? (expr2) : (expr3) 

The value is expr2 when expr1 evaluates to TRUE, and expr3 when expr1 evaluates to FALSE.

Since PHP 5.3, the middle part of the ternary operator can be omitted. The expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, otherwise returns expr3.

Example

In the following example, by checking whether the $_GET request contains a user value, it returns $_GET['user'] if present, otherwise returns nobody:

Example

<?php //Normal syntax $username = isset($_GET['user']) ? $_GET['user'] : 'nobody'; echo $username, PHP_EOL; //PHP 5.3+ version syntax $username = $_GET['user'] ?: 'nobody'; echo $username, PHP_EOL; ?>

Note:PHP_EOLis a newline character, compatible with more platforms.

In PHP 7+ versions, there is an additional NULL coalescing operator??, examples are as follows:

Example

<?php //If $_GET['user'] does not exist, return 'nobody', otherwise return the value of $_GET['user'] $username = $_GET['user'] ?? 'nobody'; //Similar ternary operator $username = isset($_GET['user']) ? $_GET['user'] : 'nobody'; ?>

Combined Comparison Operator (PHP7+)

PHP7+ supports the combined comparison operator, also called the spaceship operator, with the symbol:<=>. The combined comparison operator can easily compare two variables, and of course it is not limited to comparison of numeric data.

The syntax format is as follows:

$c = $a <=> $b;

Parsing is as follows:

  • If $a > $b, then$cthe value of1。
  • If$a == $b, then$cthe value of0。
  • If$a < $b, then$cthe value of-1。

Examples are as follows:

Example

<?php //Integer echo 1 <=> 1; // 0 echo 1 <=> 2; // -1 echo 2 <=> 1; // 1 //Floating point echo 1.5 <=> 1.5; // 0 echo 1.5 <=> 2.5; // -1 echo 2.5 <=> 1.5; // 1 //String echo "a" <=> "a"; // 0 echo "a" <=> "b"; // -1 echo "b" <=> "a"; // 1 ?>

Operator Precedence

The following table lists operators in order of precedence from high to low. Operators on the same row have the same precedence, in which case their associativity determines the order of evaluation.

Explanation: Left = left to right, right = right to left.

Associativity Operator Additional information
None clone new clone and new
Left [ array()
Right ++ -- ~ (int) (float) (string) (array) (object) (bool) @ Type and increment/decrement
None instanceof Type
Right ! Logical operators
Left * / % Arithmetic operators
Left + – . Arithmetic operators and string operators
Left << >> Bitwise operators
None == != === !== <> Comparison operators
Left & Bitwise operators and references
Left ^ Bitwise operators
Left | Bitwise operators
Left && Logical operators
Left || Logical operators
Left ? : Ternary operator
Right = += -= *= /= .= %= &= |= ^= <<= >>= => Assignment operators
Left and Logical operators
Left xor Logical operators
Left or Logical operators
Left , Used in multiple places

In operator precedence, or and ||, && and and are all logical operators with the same effect, but their precedence is different.

Example

<?php //Precedence: && > = > and //Precedence: || > = > or $a = 3; $b = false; $c = $a or $b; var_dump($c); //Here $c is an int value 3, not a boolean value true. $d = $a || $b; var_dump($d); //Here $d is a boolean value true. ?>

The output of the above examples is:

int(3)
bool(true)

Use of Parentheses

We use parentheses pairing to explicitly indicate the order of operations, rather than relying on operator precedence and associativity, which can usually increase code readability.

Example

<?php //Parentheses take precedence in operations $a = 1; $b = 2; $c = 3; $d = $a + $b * $c; echo $d; echo "\n"; $e = ($a + $b) * $c; //Using parentheses echo $e; echo "\n"; ?>

The output of the above examples is:

7
9
Other extensions