PHP Fundamentals

Operators in PHP

13 min Lesson 4 of 45

Operators in PHP

Operators are symbols that tell PHP to perform specific operations on variables and values. In this lesson, we'll explore all major types of operators and learn how to use them effectively.

Types of Operators

PHP supports the following operator categories:

1. Arithmetic Operators - Mathematical operations 2. Assignment Operators - Assigning values 3. Comparison Operators - Comparing values 4. Logical Operators - Boolean logic 5. String Operators - String concatenation 6. Increment/Decrement - Increase/decrease values 7. Conditional (Ternary) - Shorthand if-else 8. Null Coalescing - Handle null values 9. Array Operators - Array operations 10. Spaceship Operator - Three-way comparison

1. Arithmetic Operators

Used to perform mathematical calculations:

<?php $a = 10; $b = 3; // Addition echo $a + $b; // Output: 13 // Subtraction echo $a - $b; // Output: 7 // Multiplication echo $a * $b; // Output: 30 // Division echo $a / $b; // Output: 3.3333... // Modulus (remainder) echo $a % $b; // Output: 1 // Exponentiation (PHP 5.6+) echo $a ** $b; // Output: 1000 (10^3) // Negative echo -$a; // Output: -10 ?>
Practical Use: Modulus (%) is useful for checking even/odd numbers: if ($num % 2 == 0) means the number is even.

2. Assignment Operators

Used to assign values to variables:

<?php // Basic assignment $x = 10; // Add and assign $x += 5; // Same as: $x = $x + 5; Result: 15 // Subtract and assign $x -= 3; // Same as: $x = $x - 3; Result: 12 // Multiply and assign $x *= 2; // Same as: $x = $x * 2; Result: 24 // Divide and assign $x /= 4; // Same as: $x = $x / 4; Result: 6 // Modulus and assign $x %= 4; // Same as: $x = $x % 4; Result: 2 // Concatenate and assign (strings) $str = "Hello"; $str .= " World"; // Result: "Hello World" ?>
Remember: Assignment operators modify the original variable. $x += 5 changes the value of $x permanently.

3. Comparison Operators

Used to compare two values. Returns true or false:

<?php $a = 10; $b = "10"; $c = 20; // Equal (checks value only) var_dump($a == $b); // true (10 == "10") // Identical (checks value AND type) var_dump($a === $b); // false (int !== string) // Not equal var_dump($a != $c); // true var_dump($a <> $c); // true (alternative syntax) // Not identical var_dump($a !== $b); // true (different types) // Greater than var_dump($c > $a); // true (20 > 10) // Less than var_dump($a < $c); // true (10 < 20) // Greater than or equal to var_dump($c >= 20); // true // Less than or equal to var_dump($a <= 10); // true ?>
Important: Always use === (identical) instead of == (equal) when you need to check both value and type. This prevents type coercion bugs.

4. Logical Operators

Used to combine conditional statements:

<?php $x = 10; $y = 5; $z = 20; // AND - both conditions must be true if ($x > 5 && $y > 3) { echo "Both conditions are true"; } // OR - at least one condition must be true if ($x > 100 || $y < 10) { echo "At least one condition is true"; } // NOT - reverses the result if (!($x < 5)) { echo "x is NOT less than 5"; } // Alternative syntax (lower precedence) if ($x > 5 and $y > 3) { // Same as && echo "Both true"; } if ($x > 100 or $y < 10) { // Same as || echo "One is true"; } // XOR - exactly one must be true (not both) if ($x > 5 xor $y > 10) { echo "Only one condition is true"; } ?>
Best Practice: Use && and || instead of 'and' and 'or' for consistency with other programming languages and better precedence control.

5. String Operators

Used to work with strings:

<?php // Concatenation operator (.) $firstName = "John"; $lastName = "Doe"; $fullName = $firstName . " " . $lastName; echo $fullName; // Output: John Doe // Concatenation assignment (.=) $message = "Hello"; $message .= " World"; $message .= "!"; echo $message; // Output: Hello World! // Practical example $html = "<div>"; $html .= "<h1>Title</h1>"; $html .= "<p>Content</p>"; $html .= "</div>"; ?>

6. Increment/Decrement Operators

Used to increase or decrease a variable's value by 1:

<?php $x = 10; // Post-increment (use current value, then add 1) echo $x++; // Output: 10, then $x becomes 11 echo $x; // Output: 11 // Pre-increment (add 1 first, then use new value) echo ++$x; // Output: 12, $x is now 12 // Post-decrement (use current value, then subtract 1) echo $x--; // Output: 12, then $x becomes 11 // Pre-decrement (subtract 1 first, then use new value) echo --$x; // Output: 10, $x is now 10 // Common use in loops for ($i = 0; $i < 10; $i++) { echo $i; } ?>
Remember: Post-increment ($x++) uses the value first, then increments. Pre-increment (++$x) increments first, then uses the new value.

7. Conditional (Ternary) Operator

A shorthand way to write simple if-else statements:

<?php $age = 20; // Long version (if-else) if ($age >= 18) { $status = "Adult"; } else { $status = "Minor"; } // Short version (ternary) $status = ($age >= 18) ? "Adult" : "Minor"; // Syntax: (condition) ? valueIfTrue : valueIfFalse // More examples $score = 85; $grade = ($score >= 90) ? "A" : (($score >= 80) ? "B" : "C"); $isLoggedIn = true; echo $isLoggedIn ? "Welcome back!" : "Please log in"; // With HTML $hasAccess = true; echo "<div class='" . ($hasAccess ? "access-granted" : "access-denied") . "'>"; ?>
Best Practice: Use ternary operators for simple conditions. For complex logic, stick with traditional if-else for better readability.

8. Null Coalescing Operator (??) - PHP 7+

Provides a default value if a variable is null or doesn't exist:

<?php // Without null coalescing if (isset($_GET['name'])) { $name = $_GET['name']; } else { $name = "Guest"; } // With null coalescing (cleaner) $name = $_GET['name'] ?? "Guest"; // Chain multiple values $value = $config ?? $default ?? "fallback"; // Practical examples $username = $_POST['username'] ?? "Anonymous"; $page = $_GET['page'] ?? 1; $color = $userPreference ?? $defaultColor ?? "blue"; // Null coalescing assignment (PHP 7.4+) $data['key'] ??= "default value"; // Same as: $data['key'] = $data['key'] ?? "default value"; ?>
Difference from Ternary: ?? checks if the variable is null or undefined. The ternary operator ? : checks if the condition is true/false.

9. Array Operators

Used to perform operations on arrays:

<?php $arr1 = ["a" => "apple", "b" => "banana"]; $arr2 = ["b" => "blueberry", "c" => "cherry"]; // Union - combines arrays (left array values take precedence) $result = $arr1 + $arr2; // Result: ["a" => "apple", "b" => "banana", "c" => "cherry"] // Equality - true if same key/value pairs (any order) $x = ["a" => 1, "b" => 2]; $y = ["b" => 2, "a" => 1]; var_dump($x == $y); // true // Identity - true if same key/value pairs in same order and type var_dump($x === $y); // false (different order) // Inequality var_dump($x != $y); // false var_dump($x <> $y); // false // Non-identity var_dump($x !== $y); // true ?>

10. Spaceship Operator (<=>) - PHP 7+

Three-way comparison operator. Returns -1, 0, or 1:

<?php // Returns: // -1 if left is less than right // 0 if left equals right // 1 if left is greater than right echo 1 <=> 2; // Output: -1 (1 < 2) echo 2 <=> 2; // Output: 0 (2 == 2) echo 3 <=> 2; // Output: 1 (3 > 2) // Practical use: sorting $numbers = [5, 2, 8, 1, 9]; usort($numbers, function($a, $b) { return $a <=> $b; // Ascending sort }); // Result: [1, 2, 5, 8, 9] // String comparison echo "apple" <=> "banana"; // Output: -1 echo "apple" <=> "apple"; // Output: 0 ?>

Operator Precedence

When multiple operators appear in an expression, PHP follows precedence rules:

Precedence (highest to lowest): 1. ++ -- (Increment/Decrement) 2. ! (Logical NOT) 3. * / % (Multiplication, Division, Modulus) 4. + - . (Addition, Subtraction, Concatenation) 5. < <= > >= (Comparison) 6. == != === !== <=> (Equality) 7. && (Logical AND) 8. || (Logical OR) 9. ? : (Ternary) 10. = += -= *= /= .= (Assignment) Example: <?php $result = 10 + 5 * 2; // 20 (not 30) // * has higher precedence than + // Use parentheses to override $result = (10 + 5) * 2; // 30 ?>
Best Practice: When in doubt, use parentheses to make your intention clear and avoid precedence confusion.

Practical Examples

<?php // Calculate discount $price = 100; $discount = 0.15; $finalPrice = $price - ($price * $discount); // Check if number is in range $age = 25; $isValidAge = ($age >= 18 && $age <= 65); // Default value handling $username = $_POST['username'] ?? null; $displayName = $username ?? "Guest User"; // Toggle boolean $isActive = true; $isActive = !$isActive; // Now false // Calculate percentage $score = 85; $total = 100; $percentage = ($score / $total) * 100; // Round to 2 decimal places $value = 19.9567; $rounded = round($value, 2); // 19.96 // Check multiple conditions $status = "published"; $views = 1000; $isPopular = ($status === "published" && $views > 500); ?>

Practice Exercise:

Task: Create a simple calculator that:

  • Takes two numbers: $num1 = 20, $num2 = 8
  • Performs all arithmetic operations
  • Checks if $num1 is greater than $num2
  • Uses ternary to display "Even" or "Odd" for $num1
  • Calculates and displays the average of both numbers

Solution:

<?php $num1 = 20; $num2 = 8; // Arithmetic operations echo "<h3>Calculator Results</h3>"; echo "<p>Addition: " . ($num1 + $num2) . "</p>"; echo "<p>Subtraction: " . ($num1 - $num2) . "</p>"; echo "<p>Multiplication: " . ($num1 * $num2) . "</p>"; echo "<p>Division: " . ($num1 / $num2) . "</p>"; echo "<p>Modulus: " . ($num1 % $num2) . "</p>"; // Comparison $isGreater = ($num1 > $num2) ? "Yes" : "No"; echo "<p>Is $num1 greater than $num2? $isGreater</p>"; // Even or Odd $parity = ($num1 % 2 == 0) ? "Even" : "Odd"; echo "<p>$num1 is $parity</p>"; // Average $average = ($num1 + $num2) / 2; echo "<p>Average: $average</p>"; ?>

Summary

In this lesson, you learned:

  • Arithmetic operators perform mathematical calculations (+, -, *, /, %, **)
  • Assignment operators assign and modify values (=, +=, -=, *=, /=, .=)
  • Comparison operators compare values (==, ===, !=, !==, <, >, <=, >=)
  • Logical operators combine conditions (&&, ||, !)
  • String operator concatenates strings (.)
  • Increment/decrement operators modify values by 1 (++, --)
  • Ternary operator provides shorthand if-else (? :)
  • Null coalescing handles null values (??, ??=)
  • Spaceship operator performs three-way comparison (<=>)
  • Operator precedence determines evaluation order
Next Up: In the next lesson, we'll explore strings and string functions in depth - how to manipulate, search, and transform text in PHP!

ES
Edrees Salih
10 hours ago

We are still cooking the magic in the way!