PHP Operators

Operators are symbols that do something with values, like adding two numbers or comparing them. In $a + $b, the plus sign is the operator, and $a and $b are the operands.


Arithmetic operators

OperatorNameExample
+Addition$a + $b
–Subtraction$a – $b
*Multiplication$a * $b
/Division$a / $b
%Modulus (remainder)$a % $b
**Exponentiation (power)$a ** $b

Details with output are in arithmetic operators and division vs modulus.

Assignment operators

OperatorSame as
$a = 5Assign 5 to $a
$a += 3$a = $a + 3
$a -= 3$a = $a – 3
$a *= 3$a = $a * 3
$a .= “x”$a = $a . “x” (join text)
$a ??= 1Set $a only if it is not set or null

Comparison operators

OperatorNameTrue when
==EqualValues are same
===IdenticalValues and data types are same
!= or <>Not equalValues are different
!==Not identicalValues or data types are different
< , > , <= , >=Less, greater…The usual comparison
<=>SpaceshipReturns -1, 0 or 1

Learn the strict ones in == vs === and != vs !==.

Increment and decrement

++$a and $a++ add 1, --$a and $a-- subtract 1. The difference is explained in $var++ vs $var + 1.

Logical operators

OperatorNameTrue when
&& (and)AndBoth sides are true
|| (or)OrAt least one side is true
!NotThe value is false
xorXorOnly one side is true

Other useful operators

  • String join: the dot (.) joins two strings.
  • Array union: $a + $b joins two arrays.
  • Ternary: condition ? a : b. See PHP Ternary Operator.
  • Null coalescing: $a ?? "default". See the ?? operator.

Example

<?php
$a = 10;
$b = 3;

echo ($a + $b) . "<br>";
echo ($a % $b) . "<br>";
var_dump("5" == 5);
var_dump("5" === 5);
var_dump($a <=> $b);

$text = "Hello";
$text .= " PHP";
echo $text . "<br>";

$user = null;
echo $user ?? "Guest";
?>

Output:

Tutorials Class - Output Window

13
1
bool(true)
bool(false)
int(1)
Hello PHP
Guest

Note: When many operators are in one line, PHP follows an order (precedence), for example multiplication goes before addition. Use brackets to make it clear.

Next chapter: PHP Decision Making.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a PHP program to add two numbers
Write a PHP program to check whether a number is positive, negative or zero
Interview Questions & Answers
What is the difference between == and === Operators in PHP?
What are the arithmetic operators in PHP?
What is the use of the ternary operator in PHP?
What is the difference between division (/) and modulus (%) in PHP?
What is the difference between != and !== in PHP?