Session 3.3 – PHP Control Structures and Loops

Module 3: PHP Basics | Duration: 1 hr

Learning Objectives

By the end of this session, students will be able to:

  • Use conditional statements to make decisions in PHP
  • Implement if, if-else, and if-elseif-else statements
  • Use switch statements for multiple conditions
  • Apply the ternary operator for simple conditionals
  • Implement various loop structures (while, do-while, for, foreach)
  • Control loop execution using break and continue
  • Solve real-world problems using control structures

Conditional Statements

Conditional statements allow you to execute different code blocks based on certain conditions. They are fundamental to controlling program flow.

Comparison Operators

Used in conditional expressions:

Operator Description Example
==Equal to$x == $y
===Identical (equal and same type)$x === $y
!=Not equal$x != $y
!==Not identical$x !== $y
>Greater than$x > $y
<Less than$x < $y
>=Greater than or equal$x >= $y
<=Less than or equal$x <= $y

Logical Operators

Operator Description Example
&& or andBoth conditions must be true$x && $y
|| or orAt least one condition must be true$x || $y
!Negates a condition!$x

If Statement

Simple If Statement

<?phplt;?phplt;?php
    $age = 18;

    if ($age >= 18) {
        echo "You are eligible to vote.";
    }
?>

If-Else Statement

<?phplt;?phplt;?php
    $temperature = 25;

    if ($temperature > 30) {
        echo "It's hot outside!";
    } else {
        echo "The weather is pleasant.";
    }
?>
Output:
The weather is pleasant.

If-Elseif-Else Statement

<?phplt;?phplt;?php
    $score = 75;

    if ($score >= 90) {
        $grade = "A";
    } elseif ($score >= 80) {
        $grade = "B";
    } elseif ($score >= 70) {
        $grade = "C";
    } elseif ($score >= 60) {
        $grade = "D";
    } else {
        $grade = "F";
    }

    echo "Your grade is: " . $grade;
?>
Output:
Your grade is: C

Nested If Statements

<?phplt;?phplt;?php
    $age = 25;
    $hasLicense = true;

    if ($age >= 18) {
        if ($hasLicense) {
            echo "You can drive a car.";
        } else {
            echo "You need a driver's license.";
        }
    } else {
        echo "You are too young to drive.";
    }
?>

Multiple Conditions

<?phplt;?phplt;?php
    $username = "admin";
    $password = "secret123";

    if ($username == "admin" && $password == "secret123") {
        echo "Login successful!";
    } else {
        echo "Invalid credentials!";
    }

    // Using OR operator
    $role = "admin";
    if ($role == "admin" || $role == "moderator") {
        echo "Access granted to admin panel.";
    }
?>

Switch Statement

The switch statement is used to select one of many code blocks to execute based on a variable's value.

<?phplt;?phplt;?php
    $day = 3;

    switch ($day) {
        case 1:
            echo "Monday";
            break;
        case 2:
            echo "Tuesday";
            break;
        case 3:
            echo "Wednesday";
            break;
        case 4:
            echo "Thursday";
            break;
        case 5:
            echo "Friday";
            break;
        case 6:
            echo "Saturday";
            break;
        case 7:
            echo "Sunday";
            break;
        default:
            echo "Invalid day";
    }
?>
Output:
Wednesday
Important: Break Statement

The break statement is crucial in switch cases. Without it, PHP will continue executing the next cases (fall-through behavior).

Multiple Cases with Same Action

<?phplt;?phplt;?php
    $month = "February";

    switch ($month) {
        case "December":
        case "January":
        case "February":
            echo "Winter";
            break;
        case "March":
        case "April":
        case "May":
            echo "Spring";
            break;
        case "June":
        case "July":
        case "August":
            echo "Summer";
            break;
        case "September":
        case "October":
        case "November":
            echo "Fall";
            break;
        default:
            echo "Invalid month";
    }
?>

Ternary Operator

The ternary operator is a shorthand way of writing simple if-else statements.

Syntax:
$variable = (condition) ? value_if_true : value_if_false;
<?phplt;?phplt;?php
    // Traditional if-else
    $age = 20;
    if ($age >= 18) {
        $status = "Adult";
    } else {
        $status = "Minor";
    }

    // Using ternary operator (shorter)
    $status = ($age >= 18) ? "Adult" : "Minor";
    echo $status;  // Adult

    // More examples
    $score = 85;
    $result = ($score >= 50) ? "Pass" : "Fail";
    echo $result;  // Pass

    $loggedIn = true;
    $message = $loggedIn ? "Welcome back!" : "Please log in";
    echo $message;  // Welcome back!
?>

Loops in PHP

Loops allow you to execute a block of code repeatedly. PHP supports several types of loops:

while

Loops while condition is true

do-while

Executes once, then loops

for

Loops a specific number of times

foreach

Loops through array elements

While Loop

The while loop executes a block of code as long as the specified condition is true.

While Loop Syntax

<?phplt;?phplt;?php
    // Print numbers 1 to 5
    $i = 1;
    while ($i <= 5) {
        echo $i . " ";
        $i++;
    }
    // Output: 1 2 3 4 5
?>

Do-While Loop

The do-while loop executes the code block once before checking the condition.

<?phplt;?phplt;?php
    $i = 1;
    do {
        echo $i . " ";
        $i++;
    } while ($i <= 5);
    // Output: 1 2 3 4 5

    // Difference: do-while executes at least once
    $x = 10;
    do {
        echo "This runs once";
    } while ($x < 5);  // Condition is false, but code runs once
?>
While vs Do-While
  • while: Checks condition first, may not execute at all
  • do-while: Executes once, then checks condition

For Loop

The for loop is used when you know in advance how many times you want to execute a statement.

Syntax:
for (initialization; condition; increment/decrement) { // code }
<?phplt;?phplt;?php
    // Basic for loop
    for ($i = 1; $i <= 5; $i++) {
        echo $i . " ";
    }
    // Output: 1 2 3 4 5

    // Loop with step of 2
    for ($i = 0; $i <= 10; $i += 2) {
        echo $i . " ";
    }
    // Output: 0 2 4 6 8 10

    // Countdown loop
    for ($i = 5; $i >= 1; $i--) {
        echo $i . " ";
    }
    // Output: 5 4 3 2 1
?>

Practical Examples

<?phplt;?phplt;?php
    // Generate multiplication table
    $number = 5;
    for ($i = 1; $i <= 10; $i++) {
        $result = $number * $i;
        echo "$number x $i = $result<br>";
    }

    // Generate HTML list
    echo "<ul>";
    for ($i = 1; $i <= 5; $i++) {
        echo "<li>Item $i</li>";
    }
    echo "</ul>";

    // Nested for loops (pattern printing)
    for ($i = 1; $i <= 5; $i++) {
        for ($j = 1; $j <= $i; $j++) {
            echo "* ";
        }
        echo "<br>";
    }
    /* Output:
     * *
     * * *
     * * * *
     * * * * *
     */
?>

Foreach Loop

The foreach loop is specifically designed to iterate over arrays.

Foreach with Indexed Arrays

<?phplt;?phplt;?php
    $fruits = ["Apple", "Banana", "Orange", "Mango"];

    foreach ($fruits as $fruit) {
        echo $fruit . "<br>";
    }
    /* Output:
     Apple
     Banana
     Orange
     Mango
     */
?>

Foreach with Associative Arrays

<?phplt;?phplt;?php
    $student = [
        "name" => "John Doe",
        "age" => 20,
        "grade" => "A",
        "gpa" => 3.8
    ];

    foreach ($student as $key => $value) {
        echo $key . ": " . $value . "<br>";
    }
    /* Output:
     name: John Doe
     age: 20
     grade: A
     gpa: 3.8
     */
?>

Foreach with Index

<?phplt;?phplt;?php
    $colors = ["Red", "Green", "Blue"];

    foreach ($colors as $index => $color) {
        echo "Color " . ($index + 1) . ": " . $color . "<br>";
    }
    /* Output:
     Color 1: Red
     Color 2: Green
     Color 3: Blue
     */
?>

Break and Continue Statements

Break Statement

The break statement terminates the current loop immediately.

<?phplt;?phplt;?php
    // Stop loop when value is 5
    for ($i = 1; $i <= 10; $i++) {
        if ($i == 5) {
            break;  // Exit the loop
        }
        echo $i . " ";
    }
    // Output: 1 2 3 4

    // Search example
    $numbers = [10, 20, 30, 40, 50];
    $search = 30;
    $found = false;

    foreach ($numbers as $number) {
        if ($number == $search) {
            $found = true;
            break;  // No need to continue searching
        }
    }

    if ($found) {
        echo "Number $search found!";
    }
?>

Continue Statement

The continue statement skips the current iteration and continues with the next one.

<?phplt;?phplt;?php
    // Skip even numbers
    for ($i = 1; $i <= 10; $i++) {
        if ($i % 2 == 0) {
            continue;  // Skip even numbers
        }
        echo $i . " ";
    }
    // Output: 1 3 5 7 9

    // Skip negative numbers
    $numbers = [-5, 10, -3, 20, -8, 15];

    foreach ($numbers as $num) {
        if ($num < 0) {
            continue;  // Skip negative numbers
        }
        echo $num . " ";
    }
    // Output: 10 20 15
?>
Break vs Continue
  • break: Exits the entire loop
  • continue: Skips current iteration, continues with next

Session Summary

Key Points
  • Conditional statements (if, if-else, if-elseif-else) control program flow based on conditions
  • Switch statements provide an alternative to multiple if-elseif statements
  • The ternary operator offers a shorthand syntax for simple if-else statements
  • PHP supports four types of loops: while, do-while, for, and foreach
  • while loops execute as long as condition is true; do-while executes at least once
  • for loops are ideal when you know the number of iterations
  • foreach loops are specifically designed for iterating over arrays
  • break statement exits a loop; continue skips current iteration
  • Nested loops and conditional statements allow for complex logic
Next Session Preview

In the next session, we will explore PHP Arrays and Array Functions, learning how to store and manipulate collections of data efficiently.