Skip to content

Latest commit

 

History

History
274 lines (178 loc) · 5.21 KB

File metadata and controls

274 lines (178 loc) · 5.21 KB

PHP Control Structures

Control structures in PHP allow you to make decisions, repeat actions, and control the flow of your scripts.


1. Comparison Operators

Comparison operators compare two values and return either true or false.

Operator Description
== Equal (values only)
=== Identical (value and type)
!= Not equal
!== Not identical
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<=> Spaceship operator (returns -1, 0, or 1)
<> Not equal (alternative to !=)

Example

<?php

$a = 10;
$b = 20;

var_dump($a < $b);   // true
var_dump($a === 10); // true

?>

2. Logical Operators

Logical operators combine or invert conditions.

Operator Description
&& Logical AND (both conditions must be true)
`
! Logical NOT (reverses the result)
and Logical AND (lower precedence than &&)
or Logical OR (lower precedence than `
xor Logical XOR (exactly one condition must be true)

Example

<?php

$age = 25;
$citizen = true;

if ($age >= 18 && $citizen) {
    echo "Eligible to vote";
}

?>

3. if Statement

Executes code only when a condition is true.

<?php

$a = 20;
$b = 10;

if ($a > $b) {
    echo "a is larger than b";
}

?>

4. if...else Statement

Executes one block if the condition is true, otherwise another block.

<?php

$a = 5;
$b = 10;

if ($a > $b) {
    echo "a is larger than b";
} else {
    echo "a is not larger than b";
}

?>

5. if...elseif...else Statement

Checks multiple conditions in order.

<?php

$marks = 82;

if ($marks >= 90) {
    echo "Grade A";
} elseif ($marks >= 75) {
    echo "Grade B";
} elseif ($marks >= 50) {
    echo "Grade C";
} else {
    echo "Fail";
}

?>

6. Nested if Statement

An if statement inside another if statement.

<?php

$age = 22;
$hasID = true;

if ($age >= 18) {

    if ($hasID) {
        echo "Entry allowed";
    }

}

?>

7. switch Statement

Useful when checking one variable against many possible values.

<?php

$fruit = "banana";

switch ($fruit) {

    case "apple":
        echo "You chose apple";
        break;

    case "banana":
        echo "You chose banana";
        break;

    case "orange":
        echo "You chose orange";
        break;

    default:
        echo "Unknown fruit";
}

?>

Notes

  • break; stops execution after a matching case.

  • default executes if no case matches.

  • Without break, execution continues into the next case (fall-through).


8. Match Expression (PHP 8+)

match is a modern alternative to switch.

<?php

$status = 200;

$message = match ($status) {
    200 => "Success",
    404 => "Not Found",
    500 => "Server Error",
    default => "Unknown Status",
};

echo $message;

?>

Advantages

  • Uses strict comparison (===).

  • Returns a value.

  • No break statements required.

  • No accidental fall-through.


Best Practices

  • Prefer === over == to avoid unexpected type juggling.

  • Always use braces {} even for single-line if statements.

  • Use meaningful condition names and avoid deeply nested logic.

  • Always include break; in switch unless fall-through is intentional.

  • Prefer match over switch in PHP 8+ when returning values.

  • Keep conditions simple and readable by extracting complex logic into variables or functions.


Common Mistakes

  • Using == for authentication or equality checks, which triggers PHP type juggling (e.g. "0e12345" == "0e67890" evaluates to true — the "magic hash" problem) and can lead to authentication bypass.
  • Forgetting break; in a switch, causing unintended fall-through into later cases.
  • Assigning instead of comparing: writing if ($x = 5) (assignment, always true) instead of if ($x === 5).
  • Relying on loose comparison between strings and numbers, whose semantics changed in PHP 8 and can differ across versions.
  • Deeply nested if blocks that obscure logic — prefer early returns or guard clauses.

Security Considerations

  • Type juggling / loose comparison (==) is a recurring source of vulnerabilities in PHP. Always use strict comparison (===) when validating tokens, passwords, hashes, or any security-sensitive value so that values like "0e123" are not treated as numerically equal.
  • Compare secrets and hashes with constant-time, type-safe functions such as hash_equals() and password_verify() rather than ==/=== on raw strings, to resist both type juggling and timing attacks.
  • Prefer match over switch for security decisions: it uses strict comparison and has no fall-through, removing a class of logic-flaw bugs.
  • Ensure every conditional branch — including the else/default path — fails closed (denies access) so an unmatched or unexpected input never grants privileges.

Related