NeuroAgent

PHP Operators & Symbols: Complete Guide with Examples

Master all PHP operators and symbols with our comprehensive guide. Learn arithmetic, comparison, logical, and string operators with practical examples for efficient PHP programming.

Question

What do various PHP syntax symbols and operators mean, including &, &&, %, !!, @, ?:, ??, ?string, ?->, ::,
, ->, =>, ^, >>, <<, <<<, =, ==, ===, !==, !=, <>, <=>, |, ||, ~, +, +=, -=, ++, --, .=, ., , $$, `, <?=, [], <?, …, …, **, #, and #[]? Can you provide explanations and examples for each PHP operator and symbol with their respective use cases in programming?

NeuroAgent

PHP operators and symbols are fundamental building blocks that perform various operations on variables and values, ranging from arithmetic calculations and logical comparisons to string manipulations and array operations. Each symbol serves a specific purpose, with some having multiple meanings depending on context, and understanding them is essential for writing efficient, readable, and bug-free PHP code. This comprehensive guide will explain all the PHP operators and symbols you’ve listed with practical examples and use cases.

Contents


Arithmetic Operators

Addition (+)

The + operator performs addition between two numeric values.

php
$a = 5 + 3;  // $a = 8
$b = 10.5 + 2.3;  // $b = 12.8

Subtraction (-)

The - operator subtracts the right operand from the left operand.

php
$a = 10 - 4;  // $a = 6
$b = 15.7 - 3.2;  // $b = 12.5

Multiplication (*)

The * operator multiplies two numeric values.

php
$a = 6 * 7;  // $a = 42
$b = 3.5 * 2;  // $b = 7.0

Division (/)

The / operator divides the left operand by the right operand.

php
$a = 10 / 2;  // $a = 5
$b = 7 / 2;   // $a = 3.5 (floating point division)

Modulo (%)

The % operator returns the remainder of division between two numbers.

php
$a = 10 % 3;   // $a = 1 (10 divided by 3 is 3 with remainder 1)
$b = 8 % 4;    // $b = 0 (8 divided by 4 is 2 with remainder 0)
$c = -7 % 3;   // $a = -1 (negative numbers work differently)

Exponentiation (**)

The ** operator raises the left operand to the power of the right operand.

php
$a = 2 ** 3;   // $a = 8 (2^3)
$b = 4 ** 0.5; // $a = 2 (square root of 4)
$c = 5 ** -1;  // $a = 0.2 (1/5)

Bitwise Left Shift (<<)

The << operator shifts the bits of the left operand to the left by the number of positions specified by the right operand.

php
$a = 5 << 1;   // $a = 10 (binary 101 << 1 = 1010)
$b = 8 << 3;   // $a = 64 (binary 1000 << 3 = 1000000)

Bitwise Right Shift (>>)

The >> operator shifts the bits of the left operand to the right by the number of positions specified by the right operand.

php
$a = 16 >> 2;  // $a = 4 (binary 10000 >> 2 = 100)
$b = 32 >> 3;  // $a = 4 (binary 100000 >> 3 = 100)

Bitwise NOT (~)

The ~ operator inverts all bits of the operand.

php
$a = 5;        // binary: 00000101
$b = ~$a;      // $b = -6 (binary: 11111010)

Assignment Operators

Basic Assignment (=)

The = operator assigns the value of the right operand to the left operand.

php
$name = "John";
$age = 25;
$price = 19.99;

Addition Assignment (+=)

The += operator adds the right operand to the left operand and assigns the result to the left operand.

php
$a = 5;
$a += 3;  // $a = 8 (equivalent to $a = $a + 3)

Subtraction Assignment (-=)

The -= operator subtracts the right operand from the left operand and assigns the result to the left operand.

php
$a = 10;
$a -= 4;  // $a = 6 (equivalent to $a = $a - 4)

Multiplication Assignment (*=)

The *=
operator multiplies the left operand by the right operand and assigns the result to the left operand.

php
$a = 6;
$a *= 7;  // $a = 42 (equivalent to $a = $a * 7)

Division Assignment (/=)

The /= operator divides the left operand by the right operand and assigns the result to the left operand.

php
$a = 10;
$a /= 2;  // $a = 5 (equivalent to $a = $a / 2)

Modulo Assignment (%=)

The %= operator takes the modulus of the left operand with the right operand and assigns the result to the left operand.

php
$a = 10;
$a %= 3;  // $a = 1 (equivalent to $a = $a % 3)

Concatenation Assignment (.=)

The .= operator concatenates the right operand to the left operand and assigns the result to the left operand.

php
$text = "Hello";
$text .= " World";  // $text = "Hello World" (equivalent to $text = $text . " World")

Bitwise AND Assignment (&=)

The &= operator performs a bitwise AND operation between the left and right operands and assigns the result to the left operand.

php
$a = 5;   // binary: 0101
$a &= 3;  // $a = 1 (binary: 0101 & 0011 = 0001)

Bitwise OR Assignment (|=)

The |= operator performs a bitwise OR operation between the left and right operands and assigns the result to the left operand.

php
$a = 5;   // binary: 0101
$a |= 3;  // $a = 7 (binary: 0101 | 0011 = 0111)

Bitwise XOR Assignment (^=)

The ^= operator performs a bitwise XOR operation between the left and right operands and assigns the result to the left operand.

php
$a = 5;   // binary: 0101
$a ^= 3;  // $a = 6 (binary: 0101 ^ 0011 = 0110)

Bitwise Left Shift Assignment (<<=)

The <<= operator shifts the bits of the left operand to the left by the number of positions specified by the right operand and assigns the result to the left operand.

php
$a = 5;
$a <<= 1;  // $a = 10 (equivalent to $a = $a << 1)

Bitwise Right Shift Assignment (>>=)

The >>= operator shifts the bits of the left operand to the right by the number of positions specified by the right operand and assigns the result to the left operand.

php
$a = 16;
$a >>= 2;  // $a = 4 (equivalent to $a = $a >> 2)

Comparison Operators

Equal (==)

The == operator checks if two values are equal after type coercion.

php
5 == "5";     // true (string "5" is coerced to integer 5)
0 == "0";     // true
0 == false;   // true (false is coerced to 0)
"" == 0;      // true (empty string is coerced to 0)

Identical (===)

The === operator checks if two values are equal and of the same type.

php
5 === "5";    // false (different types)
5 === 5;      // true (same value and type)
false === 0;  // false (different types)

Not Equal (!=)

The != operator checks if two values are not equal after type coercion.

php
5 != "5";     // false (values are equal after coercion)
5 != 6;       // true
0 != "1";     // true

Not Identical (!==)

The !== operator checks if two values are not equal or not of the same type.

php
5 !== "5";    // true (different types)
5 !== 5;      // false (same value and type)
0 !== false;  // true (different types)

Not Equal (<>)

The <> operator is an alias for != - checks if two values are not equal after type coercion.

php
5 <> "5";     // false (values are equal after coercion)
5 <> 6;       // true

Spaceship Operator (<=>)

The <=> operator (introduced in PHP 7) returns -1, 0, or 1 when the left operand is less than, equal to, or greater than the right operand.

php
1 <=> 1;   // 0
1 <=> 2;   // -1
2 <=> 1;   // 1
"a" <=> "b";  // -1
"b" <=> "a";  // 1

Less Than (<)

The < operator checks if the left operand is less than the right operand.

php
5 < 10;    // true
10 < 5;    // false
"a" < "b"; // true (lexicographical comparison)

Greater Than (>)

The > operator checks if the left operand is greater than the right operand.

php
10 > 5;    // true
5 > 10;    // false
"b" > "a"; // true (lexicographical comparison)

Less Than or Equal To (<=)

The <= operator checks if the left operand is less than or equal to the right operand.

php
5 <= 5;    // true
5 <= 10;   // true
10 <= 5;   // false

Greater Than or Equal To (>=)

The >= operator checks if the left operand is greater than or equal to the right operand.

php
10 >= 10;  // true
10 >= 5;   // true
5 >= 10;   // false

Logical Operators

AND (&&)

The && operator returns true only if both operands are true.

php
true && true;   // true
true && false;  // false
false && true;  // false
false && false; // false

// Short-circuit evaluation
$a = false;
$b = true;
if ($a && $b) {  // $b is not evaluated because $a is false
    // code not executed
}

AND (&)

The & operator is a bitwise AND that also works as a logical operator, but doesn’t short-circuit.

php
true & true;   // true
true & false;  // false
false & true;  // false
false & false; // false

OR (||)

The || operator returns true if at least one operand is true.

php
true || true;   // true
true || false;  // true
false || true;  // true
false || false; // false

// Short-circuit evaluation
$a = true;
$b = false;
if ($a || $b) {  // $b is not evaluated because $a is true
    // code is executed
}

OR (|)

The | operator is a bitwise OR that also works as a logical operator, but doesn’t short-circuit.

php
true | true;   // true
true | false;  // true
false | true;  // true
false | false; // false

XOR (^)

The ^ operator (when used as a logical operator) returns true if exactly one operand is true.

php
true ^ true;   // false
true ^ false;  // true
false ^ true;  // true
false ^ false; // false

NOT (!)

The `` operator negates the boolean value of the operand.

php
!true;  // false
!false; // true
!0;     // true
!1;     // false
!"hello"; // false

Double Logical NOT (!!)

The !! operator converts a value to its boolean equivalent.

php
!!true;   // true
!!false;  // false
!!0;      // false
!!1;      // true
!!"hello"; // true
!!"";     // false
!!null;   // false

String Operators

Concatenation (.)

The . operator concatenates two strings.

php
$a = "Hello";
$b = " World";
$c = $a . $b;  // $c = "Hello World"

Concatenation Assignment (.=)

The .= operator appends the right operand to the left operand.

php
$text = "Hello";
$text .= " World";  // $text = "Hello World"

String Range (…)

The .. operator creates a string sequence from start to end.

php
$a = 'a'..'z';  // Creates a string containing all lowercase letters
$b = 'A'..'Z';  // Creates a string containing all uppercase letters

String Range with Step (… or …)

The ... operator (PHP 8.0+) creates a string sequence with a step.

php
$a = 'a'...'z';  // Same as .. but excludes the end value
$b = 'A'...'Z';

Increment/Decrement Operators

Pre-Increment (++$var)

The ++ operator increments the variable before using its value.

php
$a = 5;
$b = ++$a;  // $a = 6, $b = 6

Post-Increment ($var++)

The ++ operator increments the variable after using its value.

php
$a = 5;
$b = $a++;  // $a = 6, $b = 5

Pre-Decrement (–$var)

The -- operator decrements the variable before using its value.

php
$a = 5;
$b = --$a;  // $a = 4, $b = 4

Post-Decrement ($var–)

The -- operator decrements the variable after using its value.

php
$a = 5;
$b = $a--;  // $a = 4, $b = 5

Array Operators

Array Union (+)

The + operator combines two arrays, keeping the values from the left array for duplicate keys.

php
$a = [1, 2, 3];
$b = [3, 4, 5];
$c = $a + $b;  // $c = [1, 2, 3] (duplicate key 3 keeps value from $a)

Array Equality (==)

The == operator checks if arrays have the same key-value pairs.

php
$a = [1, 2, 3];
$b = [1, 2, 3];
$c = [1, 2, 4];
$a == $b;  // true
$a == $c;  // false

Array Identity (===)

The === operator checks if arrays have the same key-value pairs in the same order and of the same types.

php
$a = [1, 2, 3];
$b = [1, 2, 3];
$c = ["1", 2, 3];  // element 0 is string, not integer
$a === $b;  // true
$a === $c;  // false

Array Not Equal (!=)

The != operator checks if arrays do not have the same key-value pairs.

php
$a = [1, 2, 3];
$b = [1, 2, 4];
$a != $b;  // true

Array Not Identical (!==)

The !== operator checks if arrays do not have the same key-value pairs in the same order and of the same types.

php
$a = [1, 2, 3];
$b = [1, 2, "3"];  // element 2 is string, not integer
$a !== $b;  // true

Array Spaceship Operator (<=>)

The <=> operator compares arrays element by element.

php
$a = [1, 2, 3];
$b = [1, 2, 4];
$a <=> $b;  // -1 (at element 2, 3 < 4)

$c = [1, 2, 3];
$d = [1, 2, 3];
$c <=> $d;  // 0 (arrays are equal)

$e = [1, 2, 5];
$f = [1, 2, 3];
$e <=> $f;  // 1 (at element 2, 5 > 3)

Array Spread ([…])

The ... operator (PHP 7.4+) spreads elements of an array into another array.

php
$a = [1, 2, 3];
$b = [4, 5, ...$a];  // $b = [4, 5, 1, 2, 3]

Array Constructor ([])

The [] operator creates an empty array or an array with specified elements.

php
$a = [];          // empty array
$b = [1, 2, 3];   // array with elements
$c = ["a" => 1, "b" => 2];  // associative array

Type Operators

Type Casting (?)

The ? operator before a type name in PHP 7.0+ indicates a return type declaration.

php
function add(int $a, int $b): int {
    return $a + $b;
}

// PHP 7.0+ nullable return type
function getName(): ?string {
    return null;  // can return string or null
}

Type Casting (?->)

The ?-> operator (PHP 8.0+) is a safe property access operator that returns null if the object is null.

php
$user = null;
$name = $user?->name;  // $name = null (no error)

Type Casting (?string)

The ?string syntax indicates a nullable type (can be string or null).

php
function getName(): ?string {
    return "John Doe";  // or return null;
}

Type Casting (int), (string), (array), etc.

Type casting operators convert values to specific types.

php
(int)"123";    // 123
(string)123;   // "123"
(bool)0;       // false
(bool)1;       // true
(array)[1,2];  // [1, 2]

Error Control Operators

Error Suppression (@)

The @ operator suppresses error messages for the expression it precedes.

php
$file = @file("nonexistent.txt");  // No error displayed if file doesn't exist
if ($file === false) {
    echo "File not found";
}

Execution Operators

Backticks (`)

The operator executes the string as a shell command and returns the output.

php
$output = `ls -la`;  // Executes the ls -la command and returns its output
echo $output;

Other Important Symbols

Array Element Access (->)

The -> operator accesses a property of an object.

php
class Person {
    public $name = "John";
    public $age = 25;
}

$person = new Person();
echo $person->name;  // "John"
echo $person->age;   // 25

Static Member Access (::)

The :: operator accesses static properties and methods of a class.

php
class Math {
    public static $pi = 3.14159;
    
    public static function add($a, $b) {
        return $a + $b;
    }
}

echo Math::$pi;  // 3.14159
echo Math::add(5, 3);  // 8

List Assignment (list())

The list() construct assigns array values to multiple variables.

php
$info = ["John", "Doe", 30];
list($firstName, $lastName, $age) = $info;
echo $firstName;  // "John"
echo $lastName;   // "Doe"
echo $age;        // 30

Heredoc (<<<)

The <<< operator creates a multi-line string.

php
$text = <<<HTML
    <html>
    <head><title>Test</title></head>
    <body>Hello World</body>
    </html>
HTML;

Short Open Tag (<?=)

The <?= operator outputs the value of an expression (short echo tag).

php
<?= "Hello World" ?>  // Outputs "Hello World"

Short Open Tag (<?)

The <? operator starts a PHP block (requires short_open_tag enabled).

php
<?php
    // PHP code
?>
<?  // Alternative syntax for PHP code
    // PHP code
?>

Reference Assignment (&)

The & operator creates a reference to a variable, not a copy.

php
$a = 5;
$b = &$a;  // $b is a reference to $a
$a = 10;   // $b is now also 10

Bitwise XOR (^)

The ^ operator performs a bitwise XOR operation.

php
$a = 5;   // binary: 0101
$b = 3;   // binary: 0011
$c = $a ^ $b;  // $c = 6 (binary: 0110)

Bitwise AND (&)

The & operator performs a bitwise AND operation.

php
$a = 5;   // binary: 0101
$b = 3;   // binary: 0011
$c = $a & $b;  // $c = 1 (binary: 0001)

Bitwise OR (|)

The | operator performs a bitwise OR operation.

php
$a = 5;   // binary: 0101
$b = 3;   // binary: 0011
$c = $a | $b;  // $c = 7 (binary: 0111)

Ternary Operator (?:)

The ?: operator is a conditional operator that returns one of two values based on a condition.

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

// Null coalescing ternary (PHP 7.0+)
$name = $user['name'] ?? "Guest";
echo $name;  // "Guest" if name is null or doesn't exist

Null Coalescing Operator (??)

The ?? operator returns the first operand if it exists and is not null, otherwise returns the second operand.

php
// PHP 7.0+
$name = $user['name'] ?? "Guest";
echo $name;  // "Guest" if name is null or doesn't exist

Spaceship Operator (<=>)

The <=> operator compares two values and returns -1, 0, or 1.

php
// PHP 7.0+
$a = 10;
$b = 20;

$result = $a <=> $b;  // -1 (a < b)

$a = 20;
$b = 20;

$result = $a <=> $b;  // 0 (a == b)

$a = 30;
$b = 20;

$result = $a <=> $b;  // 1 (a > b)

Conclusion

Understanding PHP operators and symbols is fundamental to writing effective and efficient code. From basic arithmetic operations to complex bitwise manipulations, each operator serves a specific purpose that can greatly enhance your programming capabilities. The key points to remember include:

  1. Operator precedence matters - PHP has a specific order in which expressions are evaluated, which can affect your results if not properly understood.

  2. Type coercion can be tricky - The == operator performs type coercion, while === requires both value and type equality, leading to different comparison results.

  3. Short-circuit evaluation - Logical operators && and || optimize code by not evaluating the right operand when the result can be determined from the left operand alone.

  4. Null coalescing is powerful - The ?? operator simplifies null checking and provides default values in a clean, readable way.

  5. PHP 8.0+ brings new operators - The ?-> safe navigation operator and other modern operators make code more concise and less error-prone.

Mastering these operators will significantly improve your PHP programming skills and allow you to write more elegant, efficient, and maintainable code. Practice using them in different contexts to fully understand their behavior and applications.

Sources

  1. PHP: Operators - Manual
  2. PHP: Comparison Operators - Manual
  3. PHP: Arithmetic Operators - Manual
  4. PHP: String Operators - Manual
  5. PHP: Logical Operators - Manual
  6. PHP: Incrementing/Decrementing Operators - Manual
  7. PHP: Array Operators - Manual
  8. PHP: Type Operators - Manual
  9. PHP: Error Control Operators - Manual
  10. PHP: Execution Operators - Manual