Get DevWP - WordPress Development Theme

PHP Operators

In this article, I 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 use to tell the PHP processor what actions to perform. Another way to phrase it is,operators perform actions on operands and they modify values of input.

Example, in the equation “5 + 6”, the 5 and the 6 are both operands, and the + is the operator.

There are three types of operators:

  • Unary – Unary operators take just one operand
  • Binary – Binary operators take two operands
  • Ternary – Ternary operator takes three operands

PHP divides the operators in the following groups:

PHP Arithmetic Operators

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

There are 4 operators that you’re most likely familiar with which are addition, subtraction, multiplication and division. Then there’s the modulus operator which provides you the remainder from dividing two operands.

Example: 5 divided by 2. The number 2 goes into 5 only 2 times and then 1 is the remainder which is what using the modulus operator would return.

There’s also the Exponentiation (power) operator which is used to raise a base number to an exponent.

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 . "\n"; // outputs: 56
echo $x - $y . "\n"; // outputs: 44
echo $x * $y . "\n"; // outputs: 300
echo $x / $y . "\n"; // outputs: 8.3333333333333
echo $x % $y . "\n"; // outputs: 2
echo 7 ** 7 . "\n";  // outputs: 823543
echo $x ** $y . "\n"; // outputs 15625000000
?>

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; // the value 30 is represented by the variable $x
echo $x . "\n"; // Outputs: 30

$x = 40; // the value 40 is represented by the variable $x
$x += 20; // Shorthand Unary Operator
echo $x . "\n"; // Outputs: 60

$x = 80;  // the value 80 is represented by the variable $x
$x -= 30; // Shorthand Unary Operator
echo $x . "\n"; // Outputs: 50

$x = 3; // the value 3 is represented by the variable $x
$x *= 20; // Shorthand Unary Operator
echo $x . "\n"; // Outputs: 60

$x = 25;  // the value 25 is represented by the variable $x
$x /= 5; // Shorthand Unary Operator
echo $x . "\n"; // Outputs: 5

$x = 70;  // the value 70 is represented by the variable $x
$x %= 8; // Shorthand Unary Operator
echo $x . "\n"; // 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() is a PHP function that displays information about one or more expressions.
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

echo "\n";

// real world example.
$age = 20;
if ( $age >= 21 ) {
	echo "You are considered an adult and can do adult type activities. \n";
} else {
	echo "You are not considered an adult and might be limited on the type of activities you can do. \n";
}
?>

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 "\n";
echo $a;   // Outputs: 11
echo "\n";

$b = 10;
echo $b++; // Outputs: 10
echo "\n";
echo $b;   // Outputs: 11
echo "\n";

$c = 10;
echo --$c; // Outputs: 9
echo "\n";
echo $c;   // Outputs: 9
echo "\n";

$d = 10;
echo $d--; // Outputs: 10
echo "\n";
echo $d;   // Outputs: 9
echo "\n";
?>

PHP Logical Operators

Logical operators are used with conditional statements and comparison operators to determine what code should be run based on the result of the check.

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
$x = 60;  
$y = 40;

if ($x == 60 and $y == 40) {
  echo '$x is equal to 60 and $y is equal to 40.' . "\n";
} else {
  echo "Sorry, they both need to match \n";
}

if ($x == 60 && $y == 2) {
  echo "Both are true \n";
} else {
  echo "Both need to be true. \n";
}

if ($x == 60 or $y == 30) {
  echo '$x is equal to 60 or $y is equal to 30.' . "\n";
}

if ($x == 60 || $y == 30) {
  echo '$x is equal to 60 or $y is equal to 30.' . "\n";
}

if ($x == 60 xor $y == 10) {
    echo "True if either is true but not both. \n";
}

if ($x !== 55) {
  echo 'True if $x is not true' . "\n";
}
?>

PHP String Operators

PHP has Two Operators that are specifically designed for strings.

  1. Concatenation Operator ( . ) – the period symbol is used to combine both the right and left arguments.
  2. Concatenation Assignment Operator ( .= ) – the period and equals symbols are used together to append the argument on the right to the argument on the left.
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!

// the newline character is used for the terminal or viewing page source.
echo "\n";  

// use the <br> tag instead of the \n character for use in the browser. Just uncomment the line below
// echo '<br>';

$x .= $y;
echo $x; // Outputs: Hello World!

echo "\n";

// Reset the $x and $y variables
$x = "Hello";
$y = " World!";
echo $x .= $y; // Outputs: Hello World!

echo "\n";
?>

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 "\n";
echo 1 <=> 2; // Outputs: -1
echo "\n";
echo 2 <=> 1; // Outputs: 1
echo "\n";

// Comparing Floats
echo 1.5 <=> 1.5; // Outputs: 0
echo "\n";
echo 1.5 <=> 2.5; // Outputs: -1
echo "\n";
echo 2.5 <=> 1.5; // Outputs: 1
echo "\n";

// Comparing Strings
echo "x" <=> "x"; // Outputs: 0
echo "\n";
echo "x" <=> "y"; // Outputs: -1
echo "\n";
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