Skip to main content

Operators in php

Trushi Jasani
EditReport

Operators are used to perform operations on variables and values. php divides operators into several groups.

Arithmetic Operatorsโ€‹

Used to perform common mathematical operations:

OperatorNameExampleResult
+Addition$x + $ySum
-Subtraction$x - $yDifference
*Multiplication$x * $yProduct
/Division$x / $yQuotient
%Modulus$x % $yRemainder
**Exponentiation$x ** $yPower
<?php
$x = 10;
$y = 3;

echo $x + $y; // 13
echo $x - $y; // 7
echo $x * $y; // 30
echo $x / $y; // 3.333...
echo $x % $y; // 1
echo $x ** $y; // 1000
?>

Assignment Operatorsโ€‹

Used to write values to variables:

<?php
$x = 10;
$x += 5; // $x = $x + 5 โ†’ 15
$x -= 3; // $x = $x - 3 โ†’ 12
$x *= 2; // $x = $x * 2 โ†’ 24
$x /= 4; // $x = $x / 4 โ†’ 6
$x %= 4; // $x = $x % 4 โ†’ 2
?>

Comparison Operatorsโ€‹

Used to compare two values:

OperatorNameExample
==Equal$x == $y
===Identical$x === $y
!=Not equal$x != $y
!==Not identical$x !== $y
>Greater than$x > $y
<Less than$x < $y
>=Greater than or equal$x >= $y
<=Less than or equal$x <= $y
<=>Spaceship$x <=> $y
<?php
$x = 10;
$y = "10";

var_dump($x == $y); // bool(true) - same value
var_dump($x === $y); // bool(false) - different types
var_dump($x <=> 15); // int(-1) โ€” less than
?>

Increment / Decrement Operatorsโ€‹

<?php
$x = 5;
echo ++$x; // Pre-increment: 6
echo $x++; // Post-increment: 6 (then $x becomes 7)
echo --$x; // Pre-decrement: 6
echo $x--; // Post-decrement: 6 (then $x becomes 5)
?>

Logical Operatorsโ€‹

OperatorNameExample
&&And$x && $y
||Or$x || $y
!Not!$x
andAnd (low precedence)$x and $y
orOr (low precedence)$x or $y
<?php
$age = 20;
$hasID = true;

if ($age >= 18 && $hasID) {
echo "Access granted";
}
?>

String Operatorsโ€‹

<?php
$first = "Hello";
$last = "World";

echo $first . " " . $last; // Concatenation: Hello World

$str = "Hello";
$str .= " World"; // Concatenation assignment
echo $str; // Hello World
?>

Array Operatorsโ€‹

OperatorNameDescription
+UnionCombines arrays
==EqualitySame key/value pairs
===IdentitySame key/value pairs, order, and types
!=InequalityNot equal
<?php
$a = ["a" => 1, "b" => 2];
$b = ["b" => 3, "c" => 4];

$c = $a + $b;
print_r($c); // ["a" => 1, "b" => 2, "c" => 4]
?>

Ternary Operatorโ€‹

A shorthand for if...else:

<?php
$age = 20;
$status = ($age >= 18) ? "Adult" : "Minor";
echo $status; // Adult
?>

Null Coalescing Operator (??)โ€‹

Returns the first operand if it exists and is not null, otherwise returns the second operand:

<?php
$username = $_GET['user'] ?? "Guest";
echo $username; // Guest if 'user' is not set
?>
Finished reading? Mark this topic as complete.