PHP expressions
last modified May 18, 2025
In this article, we will explore expressions in PHP, a fundamental concept that drives data manipulation, decision-making, and program execution.
An expression in PHP is any combination of values, variables, operators, and function calls that evaluates to a single result. These expressions play a crucial role in PHP programming, serving as the foundation for assignments, conditional statements, loops, function calls, and mathematical computations. Every PHP script consists of expressions that determine how data is processed, stored, and executed dynamically.
PHP expressions can be categorized into different types based on their functionality:
- Arithmetic Expressions - Perform mathematical operations, such as addition, subtraction, multiplication, and division.
- String Expressions - Handle text manipulation, including concatenation and formatting.
- Boolean Expressions - Evaluate logical conditions, making them useful in conditional statements.
- Comparison Expressions - Determine equality and relational differences between values.
- Logical Expressions - Utilize operators like
&&
,||
, and!
to combine conditions. - Assignment Expressions - Store values in variables using assignment operators.
- Function Call Expressions - Execute operations that return results.
Expressions are evaluated based on operator precedence, which determines the order in which operations are performed. PHP follows standard mathematical rules for precedence, ensuring that expressions yield consistent results.
If the precedence of operators is not clear, parentheses can be used to group operations and clarify the order of evaluation. This is particularly useful when combining different types of expressions or when using multiple operators in a single expression.
Associativity is another important concept in expressions. It defines
the direction in which operators of the same precedence are evaluated. For
example, the assignment operator (=
) is right associative, meaning
that when multiple assignments are chained together, the assignment is performed
from right to left. For instance, in the expression $a = $b = 5;
,
the value 5
is first assigned to $b
, and then
$b
is assigned to $a
.
Arithmetic expressions
Arithmetic expressions perform mathematical calculations using operators like +, -, *, /, and %. They work with numeric values and follow standard mathematical precedence rules.
<?php declare (strict_types=1); $a = 10; $b = 3; // Basic operations echo "Addition: " . ($a + $b) . "\n"; echo "Subtraction: " . ($a - $b) . "\n"; echo "Multiplication: " . ($a * $b) . "\n"; echo "Division: " . ($a / $b) . "\n"; echo "Modulus: " . ($a % $b) . "\n"; echo "Exponentiation: " . ($a ** $b) . "\n"; // Compound assignments $a += 5; // $a = $a + 5 echo "After += 5: $a\n"; // Operator precedence $result = 2 + 3 * 4; // Multiplication first echo "Precedence example: $result\n";
This demonstrates basic arithmetic operations in PHP. Note how operator precedence affects evaluation order - multiplication is performed before addition unless parentheses are used.
λ php arithmetic.php Addition: 13 Subtraction: 7 Multiplication: 30 Division: 3.3333333333333 Modulus: 1 Exponentiation: 1000 After += 5: 15 Precedence example: 14
String expressions
String expressions manipulate text data. The concatenation operator (.) joins strings together. PHP also supports string interpolation in double-quoted strings.
<?php declare (strict_types=1); $firstName = "John"; $lastName = "Doe"; // Concatenation $fullName = $firstName . " " . $lastName; echo "Full name: $fullName\n"; // String interpolation $age = 30; echo "Name: $fullName, Age: $age\n"; // String functions in expressions $message = "Hello, " . strtoupper($firstName) . "!"; echo "$message\n"; // Heredoc string $html = <<<HTML <div> <h1>$fullName</h1> <p>Age: $age</p> </div> HTML; echo $html;
This shows various string operations. Note how variables are interpolated in double-quoted strings and heredoc syntax, while concatenation is needed for more complex expressions.
λ php strings.php Full name: John Doe Name: John Doe, Age: 30 Hello, JOHN! <div> <h1>John Doe</h1> <p>Age: 30</p> </div>
Comparison expressions
Comparison expressions evaluate the relationship between values and return a boolean result. PHP has both loose (==) and strict (===) comparison operators.
<?php declare (strict_types=1); $a = 5; $b = "5"; // Loose comparison (value only) echo "5 == '5': " . ($a == $b ? 'true' : 'false') . "\n"; // Strict comparison (value and type) echo "5 === '5': " . ($a === $b ? 'true' : 'false') . "\n"; // Other comparisons echo "5 != '5': " . ($a != $b ? 'true' : 'false') . "\n"; echo "5 !== '5': " . ($a !== $b ? 'true' : 'false') . "\n"; echo "5 > 3: " . ($a > 3 ? 'true' : 'false') . "\n"; // Spaceship operator (PHP 7+) echo "5 <=> 3: " . ($a <=> 3) . "\n"; // 1 echo "5 <=> 5: " . ($a <=> 5) . "\n"; // 0 echo "5 <=> 7: " . ($a <=> 7) . "\n"; // -1
This demonstrates different comparison operators. The spaceship operator returns -1, 0, or 1 depending on whether the left operand is less than, equal to, or greater than the right operand.
λ php comparison.php 5 == '5': true 5 === '5': false 5 != '5': false 5 !== '5': true 5 > 3: true 5 <=> 3: 1 5 <=> 5: 0 5 <=> 7: -1
Logical expressions
Logical expressions combine boolean values using operators like && (and), || (or), and ! (not). They're commonly used in conditional statements.
<?php declare (strict_types=1); $isLoggedIn = true; $isAdmin = false; $hasPermission = true; // AND operation if ($isLoggedIn && $hasPermission) { echo "Access granted\n"; } // OR operation if ($isAdmin || $hasPermission) { echo "Admin or privileged access\n"; } // NOT operation if (!$isAdmin) { echo "Not an admin\n"; } // Short-circuit evaluation function checkSomething() { echo "Checking...\n"; return true; } // Only first condition evaluated if false if (false && checkSomething()) { echo "This won't execute\n"; } // Only first condition evaluated if true if (true || checkSomething()) { echo "This executes without calling checkSomething()\n"; }
This shows logical operations and short-circuit evaluation. PHP stops evaluating logical expressions as soon as the final result is determined, which can prevent unnecessary function calls.
λ php logical.php Access granted Admin or privileged access Not an admin This executes without calling checkSomething()
Ternary operator
The ternary operator (?:) provides a shorthand for simple if-else statements. It evaluates a condition and returns one of two values.
<?php declare (strict_types=1); $age = 20; // Basic ternary $status = ($age >= 18) ? "Adult" : "Minor"; echo "Status: $status\n"; // Nested ternary $score = 75; $grade = ($score >= 90) ? "A" : (($score >= 80) ? "B" : (($score >= 70) ? "C" : "F")); echo "Grade: $grade\n"; // Null coalescing operator (PHP 7+) $username = $_GET['user'] ?? 'guest'; echo "Username: $username\n"; // Null coalescing assignment (PHP 7.4+) $options = []; $options['timeout'] ??= 30; echo "Timeout: {$options['timeout']}\n";
This demonstrates the ternary operator and null coalescing operators. The null coalescing operator (??) is particularly useful for providing default values when dealing with potentially undefined variables or array keys.
λ php ternary.php Status: Adult Grade: C Username: guest Timeout: 30
Operator precedence
Operator precedence determines the order in which operations are evaluated in complex expressions. Parentheses can be used to explicitly specify evaluation order.
Operators | Description | Associativity |
---|---|---|
clone new | Clone, new object | n/a |
** | Exponentiation | Right |
~ - (int) (float) (string) (array) (object) (bool) @ | Bitwise not, negation, type cast, error control | Right |
instanceof | Type check | Left |
! | Logical NOT | Right |
* / % | Multiplication, division, modulus | Left |
+ - . | Addition, subtraction, concatenation | Left |
<< >> | Bitwise shift | Left |
< <= > >= | Comparison | Non-associative |
== != === !== <> <=> | Equality, identity, comparison | Non-associative |
& | Bitwise AND | Left |
^ | Bitwise XOR | Left |
| | Bitwise OR | Left |
&& | Logical AND | Left |
|| | Logical OR | Left |
?? | Null coalescing | Left |
? : | Ternary | Right |
= += -= *= /= .= %= &= |= ^= <<= >>= **= ??= | Assignment | Right |
and | Logical AND (lower precedence) | Left |
xor | Logical XOR | Left |
or | Logical OR (lower precedence) | Left |
The table above summarizes the operator precedence in PHP. Operators with
higher precedence are evaluated first. For example, in the expression 2 + 3 * 4
,
the multiplication operator (*) has higher precedence than addition (+),
so the multiplication is performed first, resulting in 14. If you want to
force a different order of evaluation, you can use parentheses.
<?php declare (strict_types=1); // Default precedence $result = 2 + 3 * 4; echo "Default: $result\n"; // Forced precedence with parentheses $result = (2 + 3) * 4; echo "Forced: $result\n"; // Logical operator precedence $a = false; $b = true; $result = $a && $b || true; // && has higher precedence than || echo "Logical result: " . ($result ? 'true' : 'false') . "\n"; // Assignment is right-associative $x = $y = 10; echo "x: $x, y: $y\n"; // Combining operators $value = 5 * 3 + 2 ** 3; echo "Combined: $value\n";
This shows how operator precedence affects expression evaluation. Understanding precedence is important for writing correct expressions without excessive parentheses.
λ php precedence.php Default: 14 Forced: 20 Logical result: true x: 10, y: 10 Combined: 23
Operator associativity
Operator associativity determines the direction in which
operators of the same precedence are evaluated in an expression. In PHP, most
binary operators are left-associative, meaning evaluation proceeds from left to
right. Some operators, such as assignment (=
), ternary
(?:
), and exponentiation (**
), are right-associative,
so evaluation proceeds from right to left.
- Left-associative:
a - b - c
is evaluated as(a - b) - c
- Right-associative:
a = b = c
is evaluated asa = (b = c)
Associativity is important when chaining operators of the same precedence. For
example, the assignment operator is right-associative, so in $a = $b = 5;
,
$b
is assigned 5 first, then $a
is assigned
the value of $b
.
Refer to the operator precedence table above for the associativity of each operator. When in doubt, use parentheses to make the evaluation order explicit.
In this tutorial, we covered various types of expressions in PHP, including arithmetic, string, comparison, logical, and the ternary operator.
Author
List all PHP tutorials.