PHP Operators
Easy PHP Operators Guide: 7 Core Types & Examples
Master backend data manipulation with this complete PHP operators guide. Learn arithmetic, assignment, comparison, logical, string, array, and ternary operators.
Overview: Understanding PHP Operators & Evaluation Logic
Quick PHP Operators Summary:
- Definition: Operators are special symbols or keywords that take one or more data values (operands) and perform mathematical, logical, or conditional calculations.
- 7 Core Categories: PHP divides operators into Arithmetic, Assignment, Comparison, Increment/Decrement, Logical, String/Array, and Conditional (Ternary/Null Coalescing) operators.
- Strict vs. Loose Comparison: Loose operators (
==) perform automatic type coercion, whereas strict operators (===) check both value equality and data type identity. - Modern Comparison Operators: PHP 7+ introduces advanced operators like the Spaceship operator (
<=>) for three-way comparisons and the Null Coalescing operator (??) for default values. - Operator Precedence: Dictates the order in which operators are evaluated inside complex mathematical or logical expressions.
Welcome to Lesson 10 of our structured web development course, marking the beginning of Module 3: Operators & Logic Control. Following our previous lesson on Easy PHP Constants Guide: 3 Differences Between Define & Const, you now understand how server memory manages dynamic variables and immutable constants. The next essential step in building dynamic backend applications is mastering PHP operators.
In software engineering, data alone is passive. Operators are the functional engines that allow you to manipulate values, compute financial cart totals, compare user passwords during authentication, execute conditional decision-making logic, and combine dynamic text strings.
In this comprehensive PHP operators tutorial, we will explore all 7 primary operator categories, type identity rules, short-circuit evaluation mechanics, operator precedence tables, and practical strategies for writing clean, bug-free backend scripts.

Prerequisites Before Using Operators
To test the hands-on code examples in this PHP operators guide, verify that your development environment meets these basic requirements:
- Active Web Server: Running installation of Apache or Nginx with PHP 8.x+ (configured via XAMPP, Homebrew, or Terminal).
- Code Editor: A modern IDE such as Visual Studio Code or PhpStorm.
- Core Foundations: Solid understanding of variables, data types, numbers, and strings.
If you need to review how numbers and floats behave in arithmetic calculations, visit our previous guide on Easy PHP Numbers Guide: 8 Essential Math Functions & Rules.
1. Arithmetic Operators in PHP
Arithmetic operators perform standard mathematical calculationsβsuch as addition, subtraction, multiplication, division, and modulusβon numeric values (integers and floats).
| Operator | Name | Example Syntax | Result Description |
|---|---|---|---|
+ | Addition | $a + $b | Calculates the sum of two numbers. |
- | Subtraction | $a - $b | Calculates the difference between two numbers. |
* | Multiplication | $a * $b | Calculates the product of two numbers. |
/ | Division | $a / $b | Calculates the quotient (returns a float if division is not exact). |
% | Modulus | $a % $b | Calculates the integer remainder of $a divided by $b. |
** | Exponentiation | $a ** $b | Raises $a to the power of $b (PHP 5.6+). |
Arithmetic Code Example
<?php
$itemPrice = 25;
$quantity = 3;
$shippingCost = 5.50;
// Multiplication and Addition
$subtotal = $itemPrice * $quantity;
$grandTotal = $subtotal + $shippingCost;
// Modulus operator (checking if a number is even or odd)
$number = 15;
$isEven = ($number % 2 === 0);
echo "Subtotal: $" . $subtotal . "<br>";
echo "Grand Total: $" . $grandTotal . "<br>";
echo "Is 15 Even? " . ($isEven ? "Yes" : "No");
?>Want to test this code live? Try running it in our PHP Online Compiler.
2. Assignment Operators in PHP
Assignment operators write or update values in PHP variables. The basic assignment operator is =, which assigns the value of the right operand to the left variable. PHP also provides combined assignment operators that perform an operation and assign the result in a single step.
| Operator | Shorthand Example | Equivalent Full Expression | Action Performed |
|---|---|---|---|
= | $x = $y | $x = $y | Assigns value of $y to $x. |
+= | $x += $y | $x = $x + $y | Adds $y to $x and stores the sum in $x. |
-= | $x -= $y | $x = $x - $y | Subtracts $y from $x and stores the result in $x. |
*= | $x *= $y | $x = $x * $y | Multiplies $x by $y and updates $x. |
/= | $x /= $y | $x = $x / $y | Divides $x by $y and updates $x. |
%= | $x %= $y | $x = $x % $y | Calculates modulus of $x by $y and updates $x. |
.= | $txt1 .= $txt2 | $txt1 = $txt1 . $txt2 | Appends $txt2 to string $txt1. |
Assignment Code Example
<?php
$accountBalance = 100.00;
// Adding a deposit using +=
$accountBalance += 50.25; // $accountBalance is now 150.25
// Deducting a withdrawal using -=
$accountBalance -= 20.00; // $accountBalance is now 130.25
echo "Updated Account Balance: $" . $accountBalance;
?>Want to test this code live? Try running it in our PHP Online Compiler.
3. Comparison Operators & Spaceship Operator
Comparison operators compare two values and return a boolean result: either TRUE or FALSE. They are fundamental to conditional logic (e.g., if statements and loops).
Loose (==) vs. Strict (===) Comparison
Understanding the difference between loose and strict comparison is essential for security in modern backend development:
- Equal (
==): Loose comparison. Returnstrueif two values are equal after automatic type coercion (e.g.,5 == "5"evaluates totrue). - Identical (
===): Strict comparison. ReturnstrueONLY if both values are equal AND belong to the exact same data type (e.g.,5 === "5"evaluates tofalse).
| Operator | Name | Example | Returns TRUE if: |
|---|---|---|---|
== | Equal | $a == $b | $a is equal to $b (type converted). |
=== | Identical | $a === $b | $a is equal to $b AND same data type. |
!= or <> | Not Equal | $a != $b | $a is not equal to $b (type converted). |
!== | Not Identical | $a !== $b | $a is not equal to $b OR not same data type. |
> | Greater Than | $a > $b | $a is strictly greater than $b. |
< | Less Than | $a < $b | $a is strictly less than $b. |
>= | Greater Than or Equal | $a >= $b | $a is greater than or equal to $b. |
<= | Less Than or Equal | $a <= $b | $a is less than or equal to $b. |
<=> | Spaceship Operator | $a <=> $b | Returns -1 (if $a < $b), 0 (if $a == $b), or 1 (if $a > $b). |
Comparison & Spaceship Code Example
<?php
$userInputAge = "21"; // String type
$requiredAge = 21; // Integer type
// Loose comparison
var_dump($userInputAge == $requiredAge); // bool(true)
// Strict comparison
var_dump($userInputAge === $requiredAge); // bool(false)
// Spaceship operator (<=>) for array sorting / comparisons
echo (10 <=> 20) . "<br>"; // Outputs: -1 (10 < 20)
echo (20 <=> 20) . "<br>"; // Outputs: 0 (20 == 20)
echo (30 <=> 20) . "<br>"; // Outputs: 1 (30 > 20)
?>Want to test this code live? Try running it in our PHP Online Compiler.
4. Increment and Decrement Operators
Increment and decrement operators increment or decrement a variable’s integer value by 1. They are heavily used in loops and iteration counters.
- Pre-increment (
++$x): Increments$xby 1 first, then returns$x. - Post-increment (
$x++): Returns$xfirst, then increments$xby 1. - Pre-decrement (
--$x): Decrements$xby 1 first, then returns$x. - Post-decrement (
$x--): Returns$xfirst, then decrements$xby 1.
<?php
$counter = 5;
echo ++$counter . "<br>"; // Pre-increment: Increments to 6, then prints 6
echo $counter++ . "<br>"; // Post-increment: Prints 6, then increments to 7
echo $counter; // Prints 7
?>Want to test this code live? Try running it in our PHP Online Compiler.
5. Logical Operators & Short-Circuit Evaluation
Logical operators combine multiple boolean expressions to determine complex conditional outcomes.
| Operator | Name | Example | Returns TRUE if: |
|---|---|---|---|
&& or and | Logical AND | $a && $b | BOTH $a and $b are true. |
|| or or | Logical OR | $a || $b | EITHER $a or $b (or both) is true. |
! | Logical NOT | !$a | $a is NOT true (reverses boolean state). |
xor | Logical XOR | $a xor $b | EITHER $a or $b is true, but NOT both. |
Short-Circuit Evaluation
PHP uses short-circuit evaluation for logical operations:
- For
&&(AND): If the first condition isfalse, PHP skips evaluating the second condition because the overall result must be false. - For
||(OR): If the first condition istrue, PHP skips evaluating the second condition because the overall result must be true.
<?php
$isEmailVerified = true;
$hasActiveSubscription = true;
$isAccountBanned = false;
// Combining logical operators
if ($isEmailVerified && $hasActiveSubscription && !$isAccountBanned) {
echo "Access Granted to Course Portal.";
} else {
echo "Access Denied.";
}
?>Want to test this code live? Try running it in our PHP Online Compiler.
6. String & Array Operators
PHP includes specialized operators specifically designed for string manipulation and array comparison.
String Operators
- Concatenation Operator (
.): Joins two string operands. - Concatenation Assignment Operator (
.=): Appends the right string argument to the left variable.
Array Operators
Array operators allow developers to merge and compare PHP array structures:
| Operator | Name | Example | Result Description |
|---|---|---|---|
+ | Union | $x + $y | Merges array $y into $x (preserving left keys). |
== | Equality | $x == $y | Returns true if $x and $y have same key-value pairs. |
=== | Identity | $x === $y | Returns true if same key-value pairs in same order & data types. |
!= or <> | Inequality | $x != $y | Returns true if $x is not equal to $y. |
<?php
$defaults = ["theme" => "light", "show_sidebar" => true];
$userSettings = ["theme" => "dark"];
// Array union operator (+ preserves userSettings over defaults)
$finalConfig = $userSettings + $defaults;
echo "Selected Theme: " . $finalConfig['theme'] . "<br>"; // Dark
echo "Sidebar Active: " . ($finalConfig['show_sidebar'] ? "Yes" : "No");
?>Want to test this code live? Try running it in our PHP Online Compiler.
7. Conditional Operators: Ternary & Null Coalescing
Conditional operators allow developers to write clean, concise conditional evaluation assignments on a single line.
A. Ternary Operator (?:)
The ternary operator is a shorthand for simple if-else blocks. Syntax: condition ? value_if_true : value_if_false.
B. Null Coalescing Operator (??)
Introduced in PHP 7, the null coalescing operator (??) checks if a variable exists and is NOT null. If it exists, it returns that variable; otherwise, it returns a specified default fallback value.
<?php
$userLoggedIn = true;
// Ternary Operator Example
$displayStatus = $userLoggedIn ? "Welcome back!" : "Please log in.";
// Null Coalescing Operator Example
// Checks $_GET['page'] safely without throwing "Undefined index" warnings
$currentPage = $_GET['page'] ?? 1;
echo "Status: " . $displayStatus . "<br>";
echo "Current Active Page: " . $currentPage;
?>Want to test this code live? Try running it in our PHP Online Compiler.
Summary Table: All 7 PHP Operator Categories
| Category Name | Key Operators Included | Primary Application |
|---|---|---|
| Arithmetic | +, -, *, /, %, ** | Mathematical calculations, cart subtotaling, modulus checks. |
| Assignment | =, +=, -=, *=, /=, .= | Writing, updating, and appending data values in variables. |
| Comparison | ==, ===, !=, !==, >, <, <=> | Evaluating values in conditional checks and array sorting. |
| Increment / Decrement | ++$x, $x++, --$x, $x-- | Controlling loop counters and sequential sequence steps. |
| Logical | &&, ||, !, and, or, xor | Combining multiple boolean checks for access control logic. |
| String & Array | ., .=, + (array union), === | Merging text strings and comparing/merging array structures. |
| Conditional | ? : (ternary), ?? (null coalescing) | Single-line conditional evaluations and setting fallback defaults. |
Troubleshooting Common PHP Operator Errors
| Observed Error / Issue | Probable Cause | Recommended Solution |
|---|---|---|
Accidental variable assignment in if check (e.g., if ($x = 5)) | Using single = (assignment) instead of == or === (comparison). | Always use double == or strict triple === equality inside if conditions. |
Security vulnerabilities due to loose equality (==) | Loose comparison converts types automatically (e.g., "0" == false evaluates to true). | Use strict identity comparison (===) to verify both value and data type. |
| Unexpected precedence errors in complex equations | Operators evaluated in unexpected order (e.g., * taking precedence over +). | Explicitly wrap sub-expressions inside parentheses () to enforce evaluation order. |
Parse error: syntax error, unexpected '??' | Attempting to use the Null Coalescing operator on an outdated PHP version (below PHP 7.0). | Upgrade server environment to PHP 8.x+ or replace with isset($var) ? $var : $default. |
Frequently Asked Questions (FAQ)
Q1: What are PHP operators and why are they used?
PHP operators are mathematical, logical, and relational symbols used to perform operations on values and variables. They allow developers to perform math calculations, compare data, evaluate logical conditions, and control execution flow in web applications.
Q2: What is the difference between == and === in PHP?
The loose equality operator (==) checks if two values are equal after performing automatic type conversion. The strict identity operator (===) checks if two values are equal AND belong to the exact same data type without performing type conversion.
Q3: How does the Spaceship operator (<=>) work in PHP?
The Spaceship operator (<=>) performs three-way comparisons between two operands. It returns -1 if the left side is smaller, 0 if both sides are equal, and 1 if the left side is larger. It is commonly used in custom array sorting algorithms.
Q4: What is the Null Coalescing operator (??) used for?
The Null Coalescing operator (??) checks if a variable is set and not null. If the variable exists, it returns its value; otherwise, it returns a specified default fallback value (e.g., $username = $_GET['user'] ?? 'Guest';).
Next Steps & Official References
Consult official technical standards on the PHP Official Operators Manual (php.net).
Ready for the next lesson in sequence? Proceed directly to the next lesson in Module 3: Next Lesson: PHP Conditional Statements (if, else, switch) β
# Summary
Here is what you've learned in this lesson:
- Easy PHP Operators Guide: 7 Core Types & Examples
- Overview: Understanding PHP Operators & Evaluation Logic
- Prerequisites Before Using Operators
- 1. Arithmetic Operators in PHP
- 2. Assignment Operators in PHP
- 3. Comparison Operators & Spaceship Operator
- 4. Increment and Decrement Operators
- 5. Logical Operators & Short-Circuit Evaluation
- 6. String & Array Operators
- 7. Conditional Operators: Ternary & Null Coalescing
- Summary Table: All 7 PHP Operator Categories
- Troubleshooting Common PHP Operator Errors
- Frequently Asked Questions (FAQ)
- Next Steps & Official References
Continue to the next lesson and learn more about PHP Conditional Statements.
