Assignment by Value

By default, PHP assigns values by value, meaning the variable receives a copy of the data. Changing one variable does not affect the other.

$a = 5;
$b = $a; // $b is a copy of $a
$b = 10;

echo $a; // 5
echo $b; // 10

Assignment by Reference

Using the & symbol, PHP can assign a variable by reference, so both variables point to the same memory location.

$a = 5;
$b = &$a; // $b references $a
$b = 10;

echo $a; // 10
echo $b; // 10

Incrementing/Decrementing Operators

PHP supports both pre-increment/decrement and post-increment/decrement.

  • Pre (++$a, --$a): Increment/decrement before returning the value.
  • Post ($a++, $a--): Increment/decrement after returning the value.
$a = 5;
echo ++$a; // 6 (increment first, then return)
echo $a++; // 6 (return first, then increment -> $a becomes 7)
echo $a; // 7

Bitwise Operators

Bitwise operators work on binary representations of numbers.

  • & (AND)
  • | (OR)
  • ^ (XOR)
  • ~ (NOT)
  • << (shift left)
  • >> (shift right)
$a = 6;   // 110 in binary
$b = 3;   // 011 in binary

echo $a & $b; // 2 (010)
echo $a | $b; // 7 (111)
echo $a ^ $b; // 5 (101)
echo ~$a;     // -7 (two's complement)
echo $a << 1; // 12 (1100)
echo $a >> 1; // 3  (011)

Ternary Operator

The ternary operator provides a shorthand for conditional expressions:

condition ? value_if_true : value_if_false
$age = 20;
$status = ($age >= 18) ? "Adult" : "Minor";

echo $status; // Adult

Short Ternary

If the middle part is omitted, the first operand is returned if it exists.

$name = "";
$username = $name ?: "Guest"; // if $name is empty or false, "Guest" is used

echo $username; // Guest

Null Coalescing Operator

Returns the first operand if it exists and is not null; otherwise returns the second operand.

$username = $_GET['user'] ?? "Guest";
echo $username; // If no "user" in query string, outputs "Guest"

Error Control Operator: @

The @ operator suppresses error messages that would normally be displayed.

$myFile = @file("nonexistent.txt"); // No warning will be shown

if ($myFile === false) {
    echo "File not found!";
}

Execution Operator: Backticks (``)

Enclosing a command in backticks executes it as a shell command (similar to shell_exec()).

$output = `ls -l`;  // Executes "ls -l" in shell
echo $output;

instanceof Operator

Checks whether an object is an instance of a given class or implements an interface.

class Animal {}
class Dog extends Animal {}

$dog = new Dog();

var_dump($dog instanceof Dog);      // true
var_dump($dog instanceof Animal);   // true
var_dump($dog instanceof stdClass); // false

Source: Orkhan Alishov's notes