Skip to content

Operators

Overview

Operators are symbols that perform operations on variables and values. PHP provides a rich set of operators for arithmetic, comparison, logical operations, and more. This chapter covers all PHP operators with practical examples and best practices.

Arithmetic Operators

Basic Arithmetic Operations

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

echo $a + $b;  // 13 (addition)
echo $a - $b;  // 7 (subtraction)
echo $a * $b;  // 30 (multiplication)
echo $a / $b;  // 3.333... (division)
echo $a % $b;  // 1 (modulo - remainder)
echo $a ** $b; // 1000 (exponentiation, PHP 5.6+)

// Unary operators
echo +$a;      // 10 (unary plus)
echo -$a;      // -10 (unary minus)
?>

### Division and Modulo Examples
```php
<?php
// Division behavior
echo 10 / 3;    // 3.333... (float result)
echo 10 / 2;    // 5 (float result, even for integers)
echo intval(10 / 3); // 3 (integer division)

// Modulo examples
echo 10 % 3;    // 1
echo 17 % 5;    // 2
echo 8 % 4;     // 0

// Practical uses of modulo
function isEven($number) {
    return $number % 2 === 0;
}

function isOdd($number) {
    return $number % 2 === 1;
}

// Check divisibility by specific number
function isDivisibleBy($number, $divisor) {
    return $number % $divisor === 0;
}

echo isEven(4);  // true
echo isOdd(7);   // true
echo isDivisibleBy(15, 3); // true
?>

Exponentiation

php
<?php
// Exponentiation operator (PHP 5.6+)
echo 2 ** 3;     // 8 (2 to the power of 3)
echo 5 ** 2;     // 25 (5 squared)
echo 2 ** 0.5;   // 1.414... (square root of 2)

// Alternative using pow() function
echo pow(2, 3);  // 8
echo pow(5, 2);  // 25

// Large numbers
echo 2 ** 10;    // 1024
echo 2 ** 20;    // 1048576

// Fractional exponents
echo 8 ** (1/3); // 2 (cube root of 8)
echo 16 ** 0.25; // 2 (fourth root of 16)
?>

Assignment Operators

Basic Assignment

php
<?php
$x = 10;        // Basic assignment
$y = $x;        // Copy assignment
$z = &$x;       // Reference assignment

$x = 20;
echo $y;        // 10 (unchanged)
echo $z;        // 20 (changed because it's a reference)
?>

Compound Assignment Operators

php
<?php
$x = 10;

// Arithmetic assignments
$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 %= 5;        // $x = $x % 5 (1)
$x **= 3;       // $x = $x ** 3 (1, PHP 5.6+)

// String assignment
$str = "Hello";
$str .= " World";  // $str = $str . " World" ("Hello World")

// Bitwise assignments
$bits = 5;      // Binary: 101
$bits &= 3;     // $bits = $bits & 3 (1, Binary: 001)
$bits |= 2;     // $bits = $bits | 2 (3, Binary: 011)
$bits ^= 1;     // $bits = $bits ^ 1 (2, Binary: 010)
$bits <<= 1;    // $bits = $bits << 1 (4, Binary: 100)
$bits >>= 1;    // $bits = $bits >> 1 (2, Binary: 010)

// Null coalescing assignment (PHP 7.4+)
$config = null;
$config ??= 'default_value'; // Assigns only if $config is null
echo $config; // "default_value"

$config ??= 'another_value'; // Won't assign because $config is not null
echo $config; // Still "default_value"
?>

Comparison Operators

Equality and Identity

php
<?php
$a = 5;
$b = "5";
$c = 5;

// Equality (loose comparison)
var_dump($a == $b);   // true (values equal after type conversion)
var_dump($a == $c);   // true (same type and value)

// Identity (strict comparison)
var_dump($a === $b);  // false (different types)
var_dump($a === $c);  // true (same type and value)

// Inequality
var_dump($a != $b);   // false (values are equal)
var_dump($a !== $b);  // true (types are different)

// Different type examples
var_dump(0 == false);    // true
var_dump(0 === false);   // false
var_dump("" == false);   // true
var_dump("" === false);  // false
var_dump(null == false); // true
var_dump(null === false); // false
?>

Relational Operators

php
<?php
$x = 10;
$y = 20;

var_dump($x < $y);   // true (less than)
var_dump($x > $y);   // false (greater than)
var_dump($x <= $y);  // true (less than or equal)
var_dump($x >= $y);  // false (greater than or equal)

// String comparison
$str1 = "Apple";
$str2 = "Banana";
var_dump($str1 < $str2);  // true (lexicographical order)

// Array comparison
$arr1 = [1, 2, 3];
$arr2 = [1, 2, 4];
var_dump($arr1 < $arr2);  // true (element-by-element comparison)
?>

Spaceship Operator (PHP 7+)

php
<?php
// Spaceship operator returns -1, 0, or 1
echo 1 <=> 2;    // -1 (left is smaller)
echo 2 <=> 2;    // 0 (equal)
echo 3 <=> 2;    // 1 (left is larger)

// Useful for sorting
$numbers = [3, 1, 4, 1, 5, 9, 2, 6];
usort($numbers, function($a, $b) {
    return $a <=> $b; // Ascending sort
});
print_r($numbers); // [1, 1, 2, 3, 4, 5, 6, 9]

// String comparison
echo "Apple" <=> "Banana"; // -1
echo "Hello" <=> "Hello";  // 0
echo "Zebra" <=> "Apple";  // 1

// Array comparison
echo [1, 2, 3] <=> [1, 2, 4]; // -1
echo [1, 2, 3] <=> [1, 2, 3]; // 0
?>

Logical Operators

Boolean Logic

php
<?php
$x = true;
$y = false;

// AND operators
var_dump($x && $y);  // false (logical AND)
var_dump($x and $y); // false (logical AND, lower precedence)

// OR operators
var_dump($x || $y);  // true (logical OR)
var_dump($x or $y);  // true (logical OR, lower precedence)

// NOT operator
var_dump(!$x);       // false (logical NOT)
var_dump(!$y);       // true (logical NOT)

// XOR operator
var_dump($x xor $y); // true (exclusive OR)
var_dump($x xor $x); // false (same values)
?>

Short-Circuit Evaluation

php
<?php
function expensiveOperation() {
    echo "Executing expensive operation\n";
    return true;
}

$condition = false;

// Short-circuit AND - second function won't be called
if ($condition && expensiveOperation()) {
    echo "Both conditions are true\n";
}

$condition = true;

// Short-circuit OR - second function won't be called
if ($condition || expensiveOperation()) {
    echo "At least one condition is true\n";
}

// Real-world example
$user = getCurrentUser();
if ($user && $user->isActive() && $user->hasPermission('admin')) {
    // Safe chained calls - methods won't be called if $user is null
    showAdminPanel();
}
?>

Precedence Differences

php
<?php
// && vs and precedence difference
$result1 = true && false || true;  // true (evaluated as: (true && false) || true)
$result2 = true and false or true; // true (evaluated as: true and (false or true))

// Assignment with logical operators
$x = true && false;   // $x = false
$y = true and false;  // $y = true (assignment happens first)

echo $x ? 'true' : 'false'; // "false"
echo $y ? 'true' : 'false'; // "true"
?>

Increment and Decrement Operators

Prefix and Postfix Increment/Decrement

php
<?php
$i = 5;

// Prefix increment: increment first, then return value
echo ++$i; // 6 ($i is now 6)
echo $i;   // 6

$i = 5;
// Postfix increment: return value first, then increment
echo $i++; // 5 ($i becomes 6 afterwards)
echo $i;   // 6

$i = 5;
// Prefix decrement: decrement first, then return value
echo --$i; // 4 ($i is now 4)
echo $i;   // 4

$i = 5;
// Postfix decrement: return value first, then decrement
echo $i--; // 5 ($i becomes 4 afterwards)
echo $i;   // 4
?>

Practical Examples

php
<?php
// Loop counters
for ($i = 0; $i < 10; $i++) {
    echo $i . " ";
}
// Output: 0 1 2 3 4 5 6 7 8 9

// Array processing
$items = ['a', 'b', 'c', 'd'];
$index = 0;
while ($index < count($items)) {
    echo $items[$index++] . " ";
}
// Output: a b c d

// Unique ID generator
class IdGenerator {
    private static $counter = 0;
    
    public static function getNextId() {
        return ++self::$counter;
    }
}

echo IdGenerator::getNextId(); // 1
echo IdGenerator::getNextId(); // 2
echo IdGenerator::getNextId(); // 3
?>

String Operators

Concatenation

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

// Concatenation operator
$result = $first . " " . $second; // "Hello World"

// Concatenation assignment
$message = "Hello";
$message .= " ";
$message .= "World";
echo $message; // "Hello World"

// Multiple concatenations
$name = "John";
$age = 30;
$info = "Name: " . $name . ", Age: " . $age;
echo $info; // "Name: John, Age: 30"

// Concatenation with numbers
$number = 42;
$text = "The answer is " . $number;
echo $text; // "The answer is 42"
?>

String Interpolation vs Concatenation

php
<?php
$name = "Alice";
$age = 25;

// Double quotes with variable interpolation
$message1 = "Hello, $name! You are $age years old.";

// Concatenation
$message2 = "Hello, " . $name . "! You are " . $age . " years old.";

// Complex expressions (concatenation required)
$message3 = "Hello, " . strtoupper($name) . "! You are " . ($age + 1) . " next year.";

// Heredoc with interpolation
$message4 = <<<MSG
Hello, $name!
You are $age years old.
MSG;

echo $message1; // All produce the same result
?>

Array Operators

Array Union and Comparison

php
<?php
$array1 = [1, 2, 3];
$array2 = [4, 5, 6];
$array3 = [1, 2, 3];

// Array union (+ operator)
$union = $array1 + $array2;
print_r($union); // [1, 2, 3] (left array takes precedence)

$assoc1 = ['a' => 1, 'b' => 2];
$assoc2 = ['c' => 3, 'd' => 4];
$assocUnion = $assoc1 + $assoc2;
print_r($assocUnion); // ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4]

// Array equality
var_dump($array1 == $array3);  // true (same values)
var_dump($array1 === $array3); // true (same values and types)
var_dump($array1 == $array2);  // false (different values)

// Array inequality
var_dump($array1 != $array2);  // true
var_dump($array1 !== $array2); // true
?>

Array Comparison Examples

php
<?php
// Order matters for indexed arrays
$arr1 = [1, 2, 3];
$arr2 = [3, 2, 1];
var_dump($arr1 == $arr2); // false (different order)

// Order doesn't matter for associative arrays (if keys match)
$assoc1 = ['name' => 'John', 'age' => 30];
$assoc2 = ['age' => 30, 'name' => 'John'];
var_dump($assoc1 == $assoc2); // true (same key-value pairs)

// Type matters for strict comparison
$numbers1 = [1, 2, 3];
$numbers2 = ["1", "2", "3"];
var_dump($numbers1 == $numbers2);  // true (loose comparison)
var_dump($numbers1 === $numbers2); // false (strict comparison)
?>

Bitwise Operators

Basic Bitwise Operations

php
<?php
$a = 5;  // Binary: 101
$b = 3;  // Binary: 011

// Bitwise AND
echo $a & $b;  // 1 (Binary: 001)

// Bitwise OR
echo $a | $b;  // 7 (Binary: 111)

// Bitwise XOR
echo $a ^ $b;  // 6 (Binary: 110)

// Bitwise NOT
echo ~$a;      // -6 (inverts all bits)

// Left shift
echo $a << 1;  // 10 (Binary: 1010)

// Right shift
echo $a >> 1;  // 2 (Binary: 10)
?>

Practical Bitwise Examples

php
<?php
// Permission system using bitwise flags
class Permission {
    const READ = 1;    // Binary: 001
    const WRITE = 2;   // Binary: 010
    const EXECUTE = 4; // Binary: 100
    
    public static function hasPermission($userPerms, $requiredPerm) {
        return ($userPerms & $requiredPerm) === $requiredPerm;
    }
    
    public static function addPermission($userPerms, $newPerm) {
        return $userPerms | $newPerm;
    }
    
    public static function removePermission($userPerms, $removePerm) {
        return $userPerms & ~$removePerm;
    }
}

// User has READ and WRITE permissions
$userPermissions = Permission::READ | Permission::WRITE; // 3 (Binary: 011)

// Check permissions
var_dump(Permission::hasPermission($userPermissions, Permission::READ));  // true
var_dump(Permission::hasPermission($userPermissions, Permission::EXECUTE)); // false

// Add EXECUTE permission
$userPermissions = Permission::addPermission($userPermissions, Permission::EXECUTE);
var_dump(Permission::hasPermission($userPermissions, Permission::EXECUTE)); // true

// Remove WRITE permission
$userPermissions = Permission::removePermission($userPermissions, Permission::WRITE);
var_dump(Permission::hasPermission($userPermissions, Permission::WRITE)); // false
?>

Ternary and Null Coalescing Operators

Ternary Operator

php
<?php
$age = 20;

// Basic ternary
$status = ($age >= 18) ? "adult" : "minor";
echo $status; // "adult"

// Nested ternary (not recommended for readability)
$grade = 85;
$letter = ($grade >= 90) ? 'A' : (($grade >= 80) ? 'B' : (($grade >= 70) ? 'C' : 'F'));
echo $letter; // "B"

// Better approach with if-elseif
if ($grade >= 90) {
    $letter = 'A';
} elseif ($grade >= 80) {
    $letter = 'B';
} elseif ($grade >= 70) {
    $letter = 'C';
} else {
    $letter = 'F';
}

// Ternary with function calls
$user = getCurrentUser();
$username = $user ? $user->getName() : 'Guest';

// Short ternary (Elvis operator, PHP 5.3+)
$username = $user->getName() ?: 'Guest'; // If getName() is falsy, use 'Guest'
?>

Null Coalescing Operator (PHP 7+)

php
<?php
// Null coalescing operator (??)
$username = $_GET['user'] ?? $_POST['user'] ?? $_SESSION['user'] ?? 'guest';

// Equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 
           (isset($_POST['user']) ? $_POST['user'] : 
           (isset($_SESSION['user']) ? $_SESSION['user'] : 'guest'));

// Array access
$config = [
    'database' => [
        'host' => 'localhost'
    ]
];

$host = $config['database']['host'] ?? 'default_host';
$port = $config['database']['port'] ?? 3306;

// Function parameters
function createUser($name, $email = null, $role = null) {
    $email = $email ?? generateEmail($name);
    $role = $role ?? 'user';
    
    // Create user logic
}

// Null coalescing assignment (PHP 7.4+)
$cache = null;
$cache ??= expensive_operation(); // Only calls function if $cache is null
?>

Operator Precedence and Associativity

Precedence Examples

php
<?php
// Arithmetic precedence
echo 2 + 3 * 4;     // 14 (not 20, multiplication first)
echo (2 + 3) * 4;   // 20 (parentheses override precedence)

// Comparison and logical precedence
$x = 5;
$y = 10;
$z = 15;

// Comparison happens before logical AND
if ($x < $y && $y < $z) {  // Evaluated as: ($x < $y) && ($y < $z)
    echo "Values are in ascending order";
}

// Assignment and logical precedence
$result = true && false || true;  // $result = ((true && false) || true) = true
$result2 = true and false or true; // $result2 = true (assignment happens first)

// Ternary precedence
echo true ? 'yes' : false ? 'maybe' : 'no'; // "yes" (left-associative)
?>

Associativity Examples

php
<?php
// Left-associative operators
echo 10 - 5 - 2;    // 3 (evaluated as: (10 - 5) - 2)
echo 20 / 4 / 2;    // 2.5 (evaluated as: (20 / 4) / 2)

// Right-associative operators
$a = $b = $c = 10;  // Evaluated as: $a = ($b = ($c = 10))

// Exponentiation is right-associative
echo 2 ** 3 ** 2;   // 512 (evaluated as: 2 ** (3 ** 2) = 2 ** 9)

// Ternary is left-associative (unusual)
echo true ? 'a' : true ? 'b' : 'c';  // 'a' (evaluated as: (true ? 'a' : true) ? 'b' : 'c')
?>

Type Operators

instanceof Operator

php
<?php
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}

$dog = new Dog();
$cat = new Cat();

// instanceof checks
var_dump($dog instanceof Dog);    // true
var_dump($dog instanceof Animal); // true (inheritance)
var_dump($dog instanceof Cat);    // false

var_dump($cat instanceof Animal); // true
var_dump($cat instanceof Dog);    // false

// Interface checking
interface Flyable {
    public function fly();
}

class Bird implements Flyable {
    public function fly() {
        return "Flying high!";
    }
}

$bird = new Bird();
var_dump($bird instanceof Flyable); // true
var_dump($bird instanceof Bird);    // true

// String class names
$className = 'Dog';
var_dump($dog instanceof $className); // true
?>

Error Control Operator

Suppressing Errors with @

php
<?php
// Error suppression (not recommended for most cases)
$result = @file_get_contents('nonexistent_file.txt');
if ($result === false) {
    echo "File could not be read";
}

// Better approach with proper error handling
if (file_exists('data.txt')) {
    $content = file_get_contents('data.txt');
} else {
    echo "File not found";
}

// Useful for optional operations
$config = @json_decode($configString, true) ?: [];

// Division by zero suppression (still not recommended)
$result = @(10 / 0); // Returns INF instead of error
?>

Execution Operator

Backtick Operator

php
<?php
// Execute shell commands (security risk - use carefully)
$output = `ls -la`;
echo $output;

// Equivalent to shell_exec()
$output2 = shell_exec('ls -la');

// Better approach with proper escaping
$directory = '/home/user';
$safeDirectory = escapeshellarg($directory);
$output3 = shell_exec("ls -la $safeDirectory");

// Always validate and sanitize input before executing commands
function safeExecute($command, $args = []) {
    $escapedArgs = array_map('escapeshellarg', $args);
    $fullCommand = $command . ' ' . implode(' ', $escapedArgs);
    return shell_exec($fullCommand);
}
?>

Next Steps

Now that you understand PHP operators, let's explore conditional statements in Conditional Statements.

Practice Exercises

  1. Create a calculator that uses all arithmetic operators
  2. Build a permission system using bitwise operators
  3. Implement comparison functions using spaceship operator
  4. Practice operator precedence with complex expressions
  5. Create utility functions that demonstrate null coalescing

Understanding operators is crucial for writing efficient and readable PHP code!

Content is for learning and research only.