PHP Beginner

PHP Operators and Expressions

CodingerWeb
CodingerWeb
23 views 40 min read

PHP Operators and Expressions

Operators are symbols that perform operations on variables and values. PHP supports various types of operators for different operations.

Arithmetic Operators

Used to perform mathematical operations:

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

echo $a + $b;  // Addition: 13
echo $a - $b;  // Subtraction: 7
echo $a * $b;  // Multiplication: 30
echo $a / $b;  // Division: 3.333...
echo $a % $b;  // Modulus (remainder): 1
echo $a ** $b; // Exponentiation: 1000
?>

Assignment Operators

Used to assign values to variables:

<?php
$x = 10;        // Basic assignment
$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 %= 4;        // $x = $x % 4; (2)

// String concatenation assignment
$name = "John";
$name .= " Doe"; // $name = $name . " Doe"; (John Doe)
?>

Comparison Operators

Used to compare values:

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

// Equal (value only)
var_dump($a == $b);   // bool(true)

// Identical (value and type)
var_dump($a === $b);  // bool(false)

// Not equal
var_dump($a != $c);   // bool(true)
var_dump($a <> $c);   // bool(true) - alternative syntax

// Not identical
var_dump($a !== $b);  // bool(true)

// Greater than / Less than
var_dump($a > $b);    // bool(false)
var_dump($a < $c);    // bool(true)
var_dump($a >= $b);   // bool(true)
var_dump($a <= $c);   // bool(true)

// Spaceship operator (PHP 7+)
echo $a <=> $c;       // -1 (less than)
echo $c <=> $a;       // 1 (greater than)
echo $a <=> $a;       // 0 (equal)
?>

Logical Operators

Used to combine conditional statements:

<?php
$age = 25;
$hasLicense = true;
$hasInsurance = false;

// AND operator
if ($age >= 18 && $hasLicense) {
    echo "Can drive";
}

// OR operator
if ($hasLicense || $age > 21) {
    echo "Some condition met";
}

// NOT operator
if (!$hasInsurance) {
    echo "No insurance";
}

// Alternative syntax
if ($age >= 18 and $hasLicense) {
    echo "Can drive (alternative)";
}

if ($hasLicense or $age > 21) {
    echo "Some condition met (alternative)";
}
?>

Increment/Decrement Operators

<?php
$counter = 5;

// Pre-increment
echo ++$counter; // 6 (increment first, then return)

// Post-increment
echo $counter++; // 6 (return first, then increment)
echo $counter;   // 7

// Pre-decrement
echo --$counter; // 6 (decrement first, then return)

// Post-decrement
echo $counter--; // 6 (return first, then decrement)
echo $counter;   // 5
?>

String Operators

<?php
$firstName = "John";
$lastName = "Doe";

// Concatenation
$fullName = $firstName . " " . $lastName;
echo $fullName; // John Doe

// Concatenation assignment
$greeting = "Hello ";
$greeting .= $firstName;
echo $greeting; // Hello John
?>

Array Operators

<?php
$array1 = ["a", "b", "c"];
$array2 = ["d", "e", "f"];

// Union
$combined = $array1 + $array2;
print_r($combined); // ["a", "b", "c"]

// Equality
$arr1 = ["name" => "John", "age" => 25];
$arr2 = ["age" => 25, "name" => "John"];
var_dump($arr1 == $arr2);  // bool(true)
var_dump($arr1 === $arr2); // bool(false) - different order
?>

Conditional (Ternary) Operator

<?php
$age = 20;

// Traditional if-else
if ($age >= 18) {
    $status = "adult";
} else {
    $status = "minor";
}

// Ternary operator (shorthand)
$status = ($age >= 18) ? "adult" : "minor";

// Null coalescing operator (PHP 7+)
$username = $_GET['user'] ?? 'guest';

// Null coalescing assignment (PHP 7.4+)
$config['timeout'] ??= 30;
?>

Operator Precedence

Order in which operators are evaluated:

<?php
// Without parentheses
$result = 2 + 3 * 4; // 14 (multiplication first)

// With parentheses
$result = (2 + 3) * 4; // 20 (addition first)

// Complex expression
$x = 10;
$y = 5;
$z = 2;

$result = $x + $y * $z / 2 - 1; // 10 + (5 * 2) / 2 - 1 = 14
?>

Type Operators

<?php
class MyClass {}
$obj = new MyClass();

// instanceof operator
if ($obj instanceof MyClass) {
    echo "Object is instance of MyClass";
}
?>

Practical Examples

<?php
// Calculate discount
$price = 100;
$discountPercent = 15;
$discount = $price * ($discountPercent / 100);
$finalPrice = $price - $discount;

echo "Original: $" . $price . "
";
echo "Discount: $" . $discount . "
";
echo "Final: $" . $finalPrice . "
";

// Grade calculator
$score = 85;
$grade = ($score >= 90) ? "A" : 
         (($score >= 80) ? "B" : 
         (($score >= 70) ? "C" : 
         (($score >= 60) ? "D" : "F")));

echo "Score: $score, Grade: $grade";
?>

Practice Exercise

Create a simple calculator that:

  • Takes two numbers
  • Performs all arithmetic operations
  • Compares the numbers
  • Uses ternary operator to determine which is larger

Key Takeaways

  • Different operators serve different purposes
  • Understand operator precedence
  • Use parentheses for clarity
  • === checks both value and type
  • Ternary operator provides concise conditionals