Get DevWP - WordPress Development Theme

PHP Operators

In this article, I’ll show you how to manipulate and perform operations on variables and values using PHP Operators.

What are Operators in PHP?

Operators are the symbols you’ll use to to tell the PHP processor what actions to perform.

PHP divides the operators in the following groups:

PHP Arithmetic Operators

PHP Arithmetic Operators are used with numbers to perform mathematical operations as described below.

OperatorDescriptionExampleResult
+Addition$x + $ySum of $x and $y
Subtraction$x – $yDifference of $x and $y
*Multiplication$x * $yProduct of $x and $y
/Division$x / $yQuotient of $x and $y
%Modulus$x % $yRemainder of $x divided by $y
**Exponentiation$x ** $yResult of raising $x to the $y’th power


<?php
$x = 50;
$y = 6;
echo $x + $y . '<br>'; // outputs: 56
echo $x - $y . '<br>'; // outputs: 44
echo $x * $y . '<br>'; // outputs: 300
echo $x / $y . '<br>'; // outputs: 8.3333333333333
echo $x % $y . '<br>'; // outputs: 2
?>

PHP Assignment Operators

PHP Assignment Operators are used to assign values to variables using what you might think of as the equal sign =, in PHP is the Assignment Operator.
What this means is the Operand on the left of the Assignment Operator = gets assigned the value of what’s on the right of the Assignment Operator = as described below.

OperatorDescriptionExampleSame As
=x gets set to the value of the expression y on the right$x = $y$x = $y
+=Addition$x += $y$x = $x + $y
-=Subtractraction$x -= $y$x = $x – $y
*=Multiplication$x *= $y$x = $x * $y
/=Division$x /= $y$x = $x / $y
%=Modulus$x %= $y$x = $x % $y

<?php
$x = 30;
echo $x . '<br>'; // Outputs: 30

$x = 40;
$x += 20;
echo $x . '<br>'; // Outputs: 60

$x = 80;
$x -= 30;
echo $x . '<br>'; // Outputs: 50

$x = 3;
$x *= 20;
echo $x . '<br>'; // Outputs: 60

$x = 25;
$x /= 5;
echo $x . '<br>'; // Outputs: 5

$x = 70;
$x %= 8;
echo $x . '<br>'; // Outputs: 6
?>


PHP Comparison Operators

PHP Comparison Operators are used to compare two values in a Boolean fashion.

OperatorNameExampleResult
==Equal$x == $yTrue if $x is equal to $y
===Identical$x === $yTrue if $x is equal to $y, and they are of the same type
!=Not equal$x != $yTrue if $x is not equal to $y
<>Not equal$x <> $yTrue if $x is not equal to $y
!==Not identical$x !== $yTrue if $x is not equal to $y, or they are not of the same type
<Less than$x < $yTrue if $x is less than $y
>Greater than$x > $yTrue if $x is greater than $y
>=Greater than or equal to$x >= $yTrue if $x is greater than or equal to $y
<=Less than or equal to$x <= $yTrue if $x is less than or equal to $y

<?php
$x = 70;
$y = 60;
$z = "70";

var_dump( $x == $z );  // Outputs: boolean true
var_dump( $x === $z ); // Outputs: boolean false
var_dump( $x != $y );  // Outputs: boolean true
var_dump( $x !== $z ); // Outputs: boolean true
var_dump( $x < $y );   // Outputs: boolean false
var_dump( $x > $y );   // Outputs: boolean true
var_dump( $x <= $y );  // Outputs: boolean false
var_dump( $x >= $y );  // Outputs: boolean true

?>

PHP Incrementing and Decrementing Operators

The increment/decrement operators are used to increment/decrement a variable’s value.

OperatorNameEffect
++$xPre-incrementIncrements $x by one, then returns $x
$x++Post-incrementReturns $x, then increments $x by one
--$xPre-decrementDecrements $x by one, then returns $x
$x--Post-decrementReturns $x, then decrements $x by one

<?php
$a = 10;
echo ++ $a; // Outputs: 11
echo '<br>';
echo $a;   // Outputs: 11
echo '<br>';

$b = 10;
echo $b ++; // Outputs: 10
echo '<br>';
echo $b;   // Outputs: 11
echo '<br>';

$c = 10;
echo -- $c; // Outputs: 9
echo '<br>';
echo $c;   // Outputs: 9
echo '<br>';

$d = 10;
echo $d --; // Outputs: 10
echo '<br>';
echo $d;   // Outputs: 9
echo '<br>';
?>

PHP Logical Operators

The logical operators are used to combine conditional statements.

OperatorNameExampleResult
andAnd$x and $yTrue if both $x and $y are true
orOr$x or $yTrue if either $x or $y is true
xorXor$x xor $yTrue if either $x or $y is true, but not both
&&And$x && $yTrue if both $x and $y are true
||Or$x || $yTrue if either $x or $y is true
!Not!$xTrue if $x is not true

<?php
$age = 21;
if ( $age == 21 ) {
	echo "You are $age years old.";
} else {
	echo "You are not $age years old.";
}
?>

Output from above is You are 21 years old.


PHP String Operators

PHP has Two Operators that are specifically designed for strings.

OperatorDescriptionExampleResult
.Concatenation$a . $bConcatenation of $a and $b
.=Concatenation assignment$a .= $bAppends $b to $a


<?php
$x = "Hello";
$y = " World!";
echo $x . $y; // Outputs: Hello World!

$x .= $y;
echo $x; // Outputs: Hello World!
echo '<br>';
// Reset the $x and $y variables
$x = "Hello";
$y = " World!";
echo $x .= $y; // Outputs: Hello World!
?>

PHP Array Operators

The array operators are used to compare arrays:

OperatorNameExampleResult
+Union$x + $yUnion of $x and $y
==Equality$x == $yTrue if $x and $y have the same key/value pairs
===Identity$x === $yTrue if $x and $y have the same key/value pairs in the same order and of the same types
!=Inequality$x != $yTrue if $x is not equal to $y
<>Inequality$x <> $yTrue if $x is not equal to $y
!==Non-identity$x !== $yTrue if $x is not identical to $y

Checkout the Code example below:



<?php
$x = array( "a" => "Red", "b" => "Green", "c" => "Blue" );
$y = array( "u" => "Yellow", "v" => "Orange", "w" => "Pink" );
$z = $x + $y; // Union of $x and $y
var_dump( $z );
var_dump( $x == $y );   // Outputs: boolean false
var_dump( $x === $y );  // Outputs: boolean false
var_dump( $x != $y );   // Outputs: boolean true
var_dump( $x <> $y );   // Outputs: boolean true
var_dump( $x !== $y );  // Outputs: boolean true
?>

PHP Spaceship Operator New in PHP 7

PHP 7 introduced the spaceship operator (<=>) which can be used for comparing two expressions. It’s also known as combined comparison operator.

The Spaceship Operator returns -1 if $a < $b, 0 if $a is equal $b, 1 if $a > $b.

Checkout the Table Below:

Spaceship Operator <=>Equivalent To
($x <=> $y) === -1$x < $y
($x <=> $y) === -1 || ($x <=> $y) === 0$x <= $y
($x <=> $y) === 0$x == $y
($x <=> $y) !== 0$x != $y
($x <=> $y) === 1 || ($x <=> $y) === 0$x >= $y
($x <=> $y) === 1$x > $y

Checkout the example code below:



<?php
// Comparing Integers
echo 1 <=> 1; // Outputs: 0
echo '<br>';
echo 1 <=> 2; // Outputs: -1
echo '<br>';
echo 2 <=> 1; // Outputs: 1
echo '<br>';

// Comparing Floats
echo 1.5 <=> 1.5; // Outputs: 0
echo '<br>';
echo 1.5 <=> 2.5; // Outputs: -1
echo '<br>';
echo 2.5 <=> 1.5; // Outputs: 1
echo '<br>';

// Comparing Strings
echo "x" <=> "x"; // Outputs: 0
echo '<br>';
echo "x" <=> "y"; // Outputs: -1
echo '<br>';
echo "y" <=> "x"; // Outputs: 1
?>

PHP Conditional Assignment Operators

The PHP conditional assignment operators are used to set a value depending on conditions:

OperatorNameExampleResult
?:Ternary$x = expr1 ? expr2 : expr3Returns the value of $x.
The value of $x is expr2 if expr1 = TRUE.
The value of $x is expr3 if expr1 = FALSE
??Null coalescing$x = expr1 ?? expr2Returns the value of $x.
The value of $x is expr1 if expr1
exists, and is not NULL.
If expr1 does not exist, or is NULL, the value of $x is expr2.
Introduced in PHP 7

Checkout the example code below:



<?php
$var = 5;
// Ternary operator example
$var2 = $var > 2 ? 'yes' : 'no'; // returns yes
echo $var2;
?>

Below is an example if you were attempting to retrieve a value using Get or Post from a form and database.
We try out Null Coalescing and then Ternary Operator.



<?php
// Fetches the value of $_GET['user']
// and returns 'nobody'if it doesn't exist.

// Null Coalescing example
$username = $_GET['user'] ?? 'nobody';

// This is equivalent to:
// Ternary operator example
$username = isset( $_GET['user'] ) ? $_GET['user'] : 'nobody';

// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>

Let’s try various conditional examples


if isset else example.


<?php
 $name1 = 'Jay';
if ( isset( $name1 ) ) {
	echo $name1;
} else {
	echo '$name1 variable not set';
}
?>

Output from above: Jay

Using the ternary operator to achieve the same result.


<?php
$name2 = 'Jay';
echo $namecheck = isset( $name2 ) ? $name2 : '$name2 variable not set';
?>

Output from above: Jay

Use Null coalescing to achieve the same result.


<?php
$name3 = 'Jay';
echo $namechk = $name3 ?? '$name3 variable not set';
?>

Output from above: Jay

This operator can also be chained (with right-associative semantics):


<?php
$example1 = null;
$example2 = null;
echo $output = $example1 ?? $example2 ?? '$example1 and $example2 are null';
?>

Output from above: $example1 and $example2 are null

Which is the same as:


<?php
$example1 = null;
$example2 = null;
if ( isset( $example1 ) ) {
	echo $example1;
} elseif ( isset( $example2 ) ) {
	echo $example2;
} else {
	echo '$example1 and $example2 are null';
}
?>

Output from above: $example1 and $example2 are null


PHP Operator Precedence

Operator Precedence is based on PEMDAS:

  • Parenthesis
  • Exponents
  • Multiplication
  • Division
  • Addition
  • Subtraction

For example, 5 + 4 * 2 = 13 not 18. If you want to force a certain precedence, you would wrap your equation in parenthesis like so: (5 + 4) * 2 = 18 not 13


<?php
		echo 5 + 4 * 2; // 13
		echo '<br>';
		echo (5 + 4) * 2; // 18
?>

Operator Precedence Table

AssociativityOperatorsAdditional Info
non-associativeclone
new
clone and new
right**arithmetic
right ++

~
(int)
(float)
(string)
(array)
(object)
(bool)
@
types and increment/decrement
non-associativeinstanceoftypes
right!logical
left *
/
%
arithmetic
left +

.
arithmetic and string
left <<>>bitwise
non-associative <
<=
>
>=
comparison
non-associative ==
!=
===
!==
<>
<=>
comparison
left&bitwise and references
left^bitwise
left|bitwise
left&&logical
left||logical
right??null coalescing
left? :ternary
right =
+=
-=
*=
**=
/=
.=
%=
&=
|=
^=
<<=
>>=
assignment
rightyield fromyield from
rightyieldyield
leftandlogical
leftxorlogical
leftorlogical

PHP Operators Recap

PHP Operators include:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Increment and Decrement operators
  • Logical operators
  • String operators
  • Array operators
  • Spaceship Operator
  • Conditional Assignment operators

PHP Operator Precedence follows PEMDAS:

  • Parenthesis
  • Exponents
  • Multiplication
  • Division
  • Addition
  • Subtraction

Hopefully this tutorial helped you understand PHP Operators.



View Our Themes

Let's Connect