<< Home

Chapter 4: Operators and Expressions

Operators form the building blocks of expressions. They allow you to combine, compare, and manipulate values. PHP supports a wide variety of operators, many inherited from C-style languages, and a few unique ones such as the spaceship and null coalescing operators. Understanding how operators work and how they interact through precedence rules is key to writing predictable code.

💡 In PHP, almost everything that produces a value is an expression. You can often assign, compare, or combine values directly inside other statements.

Arithmetic and Assignment

Arithmetic operators perform mathematical calculations on numbers. Assignment operators store values in variables and can combine with arithmetic operations for concise updates.

Basic arithmetic operations

PHP supports addition, subtraction, multiplication, division, modulus, and exponentiation.

$a = 10;
$b = 3;

echo $a + $b;   // 13
echo $a - $b;   // 7
echo $a * $b;   // 30
echo $a / $b;   // 3.3333...
echo $a % $b;   // 1
echo $a ** $b;  // 1000
⚠️ Division always produces a float, even when the result appears whole. Use intdiv() for integer division.

Compound assignment operators

Compound operators perform an operation and assignment together. They simplify repetitive updates.

$x = 5;
$x += 2;  // 7
$x *= 3;  // 21
$x -= 1;  // 20

Increment and decrement

You can increase or decrease a numeric variable by one using ++ and --. Prefix form modifies the variable before use; postfix form after use.

$y = 10;
echo ++$y;  // 11
echo $y--;  // prints 11, then becomes 10

Comparison and Spaceship Operator

Comparison operators check relationships between values and return a boolean result. PHP includes standard relational operators as well as a three-way comparison operator known as the spaceship operator.

Standard comparison operators

Use equality == and identity === to test for value or type match. Use inequality != and !== to test for non-matches. Relational operators <, >, <=, and >= work with numbers and strings.

$a = 5;
$b = "5";

var_dump($a == $b);   // true (values are equal)
var_dump($a === $b);  // false (different types)
💡 Prefer === and !== for reliable results that do not rely on automatic type conversion.

Using the spaceship operator <=>

The spaceship operator compares two expressions and returns -1, 0, or 1 depending on whether the left-hand side is less than, equal to, or greater than the right-hand side. It simplifies sorting logic and custom comparisons.

echo 5 <=> 10;   // -1
echo 10 <=> 10;  // 0
echo 15 <=> 10;  // 1

Logical and Bitwise Operations

Logical operators evaluate boolean expressions, while bitwise operators manipulate individual bits in integer values. Both are essential in control flow and low-level programming tasks.

Using logical operators for flow control

Logical operators combine boolean values. && and || short-circuit, meaning they skip evaluating the second operand when the result is already known.

$a = true;
$b = false;

if ($a && !$b) {
  echo "Only a is true";
}

Bitwise manipulation of integers

Bitwise operators act on binary representations of integers. They are useful for flag-based systems and binary masks.

$x = 6;        // 110
$y = 3;        // 011

echo $x & $y;  // 2 (010)
echo $x | $y;  // 7 (111)
echo $x ^ $y;  // 5 (101)
echo ~$x;      // bitwise NOT
⚠️ Bitwise operations convert operands to integers automatically. Floating point or string values will be coerced, sometimes producing unexpected results.

String Operators

Strings can be combined using the concatenation operator or concatenation assignment. PHP does not have arithmetic on strings, so these are the main tools for string assembly.

Concatenating strings with .

Use the dot operator to join strings together. It works with both literals and variables.

$first = "Hello";
$second = "World";
echo $first . " " . $second;

Using concatenation assignment

The concatenation assignment operator .= appends text directly to an existing variable.

$message = "Hello";
$message .= " there";
$message .= "!";
echo $message;  // Hello there!

Null Coalescing and Ternary

PHP includes concise operators for handling optional or conditional values. The null coalescing operator and ternary operator are common in compact control expressions.

Handling defaults with null coalescing ??

Use ?? to return the first operand that is not null. It is ideal for working with optional array keys or request parameters.

$user = $_GET["user"] ?? "Guest";
echo $user;

Writing compact conditionals with the ternary operator

The ternary operator evaluates a condition and selects between two values. Its syntax is condition ? if_true : if_false.

$age = 20;
$status = ($age >= 18) ? "Adult" : "Minor";
echo $status;
💡 PHP also supports a shorthand ternary form $x ?: "default", which returns the left-hand value if it is truthy, otherwise the right-hand value.

Operator Precedence and Associativity

When multiple operators appear in a single expression, precedence and associativity determine evaluation order. Higher precedence operators run before lower ones; associativity decides whether evaluation proceeds left-to-right or right-to-left for operators of equal precedence.

Understanding precedence rules

For example, multiplication has higher precedence than addition, so it executes first unless you override it with parentheses.

echo 2 + 3 * 4;    // 14
echo (2 + 3) * 4;  // 20

Associativity of assignment and concatenation

Most operators are left-associative, meaning they evaluate from left to right. Assignment and concatenation are right-associative, so evaluation happens from right to left.

$a = $b = 5;
echo $a;  // 5

Operator precedence table for quick reference

The following table lists common operators from highest to lowest precedence. Operators on the same line share the same precedence and are evaluated in the same order according to their associativity.

OperatorsAssociativity
clone, newLeft
**Right
!, ~, ++, --, +, - (unary)Right
*, /, %Left
+, -, .Left
<<, >>Left
<, <=, >, >=Left
==, !=, ===, !==, <=>Left
&Left
^Left
|Left
&&Left
||Left
??Right
? : (ternary)Left
=, +=, -=, *=, /=, .=, %=, &=, |=, ^=, <<=, >>=Right
andLeft
xorLeft
orLeft
💡 The and, or, and xor keywords have lower precedence than && and ||. Use them sparingly to avoid unexpected results in compound conditions.

Remember that parentheses are always the clearest and safest way to control evaluation explicitly.