Contents

Control Statement

PHP Decision Making

PHP enables us to execute specific actions based on conditions, which may involve logical or comparative evaluations. Depending on the outcome of these conditions, either TRUE or FALSE, a corresponding action will be taken. Think of it like a two-way path: if a condition is met, proceed one way; otherwise, go the other way. PHP provides us with four key conditional statements to handle such logic:

  • if statement
  • if…else statement
  • if…elseif…else statement
  • switch statement

Let’s take a closer look at each of these:

1. if Statement: This statement evaluates a condition, and if it returns TRUE, the block of code inside the if clause is executed.

Syntax:

				
					if (condition) {
    // If TRUE, execute this code
}

				
			

Example

				
					<?php 
$number = 25;

if ($number > 10) {
    echo "The number is greater than 10";
}
?>

				
			

Output:

				
					The number is greater than 10

				
			

2. if…else Statement: We know that when a condition holds TRUE, the code inside the if block gets executed. But what happens if the condition is FALSE? That’s where else comes in. If the condition is TRUE, the if block is executed; otherwise, the else block runs.

				
					if (condition) {
    // If TRUE, execute this code
} else {
    // If FALSE, execute this code
}
/
				
			

Example:

				
					<?php 
$temperature = -5;

if ($temperature >= 0) {
    echo "The temperature is above freezing";
} else {
    echo "The temperature is below freezing";
}
?>

				
			

Output:

				
					The temperature is below freezing

				
			

3. if…elseif…else Statement: This structure allows for multiple if and else conditions. It is useful when we have more than two possible scenarios to check.

Syntax:

				
					if (condition1) {
    // If TRUE, execute this code
} elseif (condition2) {
    // If TRUE, execute this code
} elseif (condition3) {
    // If TRUE, execute this code
} else {
    // If none are TRUE, execute this code
}

				
			

Output:

				
					<?php 
$month = "March";

if ($month == "January") {
    echo "Start of the year";
} elseif ($month == "March") {
    echo "It's March!";
} elseif ($month == "December") {
    echo "End of the year";
} else {
    echo "Just another month";
}
?>

				
			

Output:

				
					It's March!

				
			

4. switch Statement: The switch statement provides an efficient way to compare an expression to multiple values (cases) and execute the matching case. The break keyword is used to prevent fall-through, and the default keyword handles cases where no match is found.

Syntax:

				
					switch(expression) {
    case value1:
        // Code to be executed if expression == value1;
        break;
    case value2:
        // Code to be executed if expression == value2;
        break;
    ...
    default:
        // Code to be executed if no case matches
}

				
			

Example:

				
					<?php 
$day = "Tuesday";

switch($day) {
    case "Monday":
        echo "Start of the week!";
        break;
    case "Tuesday":
        echo "It's Tuesday";
        break;
    case "Wednesday":
        echo "Midweek";
        break;
    default:
        echo "Not a specific day";
}
?>

				
			

Output:

				
					It's Tuesday

				
			

PHP switch Statement

The switch statement in PHP works similarly to multiple if-else conditions. It checks an expression against several predefined cases and executes the code in the matching case block. The evaluation starts with the expression, and it is then compared with the value of each case. When a match is found, the corresponding block of code is executed.

Two essential components of the switch statement are:

  • break: This stops the code execution from flowing into subsequent cases after the correct case has been executed.
  • default: This block of code runs if no case matches the expression.

Syntax:

				
					switch(expression) {
    case value1:
        // Code block
        break;
    case value2:
        // Code block
        break;
    // More cases as needed
    default:
        // Code block if no case matches
}

				
			

Example 1:

This example demonstrates how the switch statement works by evaluating an integer.

				
					<?php
$day = 4;

switch ($day) {
    case 1:
        echo "It's Monday";
        break;
    case 2:
        echo "It's Tuesday";
        break;
    case 3:
        echo "It's Wednesday";
        break;
    case 4:
        echo "It's Thursday";
        break;
    case 5:
        echo "It's Friday";
        break;
    default:
        echo "It's the weekend!";
}
?>

				
			

Output:

				
					It's Thursday

				
			

Example 2:

This example demonstrates a switch with characters and multiple cases grouped together.

				
					<?php
$grade = 'E';

switch ($grade) {
    case 'A':
    case 'B':
        echo "Excellent or Good";
        break;
    case 'C':
    case 'D':
        echo "Average or Below Average";
        break;
    case 'E':
    case 'F':
        echo "Needs Improvement";
        break;
    default:
        echo "Unknown grade";
}
?>

				
			

Output:

				
					Needs Improvement

				
			

PHP break (Single and Nested Loops)

Break in PHP

In PHP, the break statement is used to exit a loop prematurely when a certain condition is met. Once the loop is broken, the control of the program moves to the statement immediately following the loop.

Method 1: Breaking a loop when a specific value is encountered

The goal is to iterate through an array and display its elements, but stop the loop when a specific value (in this case, 5) is found.

Example 1:

				
					<?php
// Array declaration
$numbers = array(2, 4, 5, 8, 10);

// Using a foreach loop
foreach ($numbers as $num) {
    if ($num == 5) {
        break; // Terminates loop when 5 is found
    }
    echo $num . " ";
}
echo "\nLoop Terminated";
?>

				
			

Output:

				
					2 4
Loop Terminated

				
			

Method 2: Breaking out of nested loops

When working with nested loops, you can use break 2 to exit both loops simultaneously. Here’s an example where we display values from two arrays, but stop once a value in the first array matches a value in the second array.

Example 2:

				
					<?php
// Declaring two arrays
$letters1 = array('X', 'Y', 'Z');
$letters2 = array('Z', 'Y', 'X');

// Outer loop through the first array
foreach ($letters1 as $l1) {
    echo "$l1 ";

    // Inner loop through the second array
    foreach ($letters2 as $l2) {
        if ($l1 != $l2) {
            echo "$l2 ";
        } else {
            break 2; // Break out of both loops when a match is found
        }
    }
    echo "\n";
}

echo "\nLoop Terminated";
?>

				
			

Output:

				
					X Z Y 
Loop Terminated

				
			

PHP continue Statement

The continue statement is used in loops to skip the current iteration and move to the next one, without terminating the loop. It helps bypass the remaining code in the loop for the current iteration and proceeds with the next one.

In PHP, continue can take an optional numeric argument, which specifies how many loop levels to skip. The default value is 1, meaning it skips the current iteration of the innermost loop.

Syntax:

				
					loop {
    // Some statements
    ...
    continue;
}

				
			

Example 1: Skipping even numbers using continue

This example demonstrates how the continue statement can be used in a for loop to skip even numbers and only print the odd ones.

				
					<?php
for ($num = 1; $num <= 10; $num++) {
    if ($num % 2 == 0) {
        continue; // Skip the current iteration for even numbers
    }
    echo $num . " ";
}
?>

				
			

Output:

				
					1 3 5 7 9

				
			

Example 2: Using continue 2 to skip outer loop iterations

The following example shows how continue 2 is used in nested loops. It skips the current iteration of both the inner and outer loops, moving to the next iteration of the outer loop.

				
					<?php
$num = 3;

while ($num++ < 4) {
    echo "Outer Loop\n";

    while (true) {
        echo "Inner Loop\n";
        continue 2; // Skips the next iteration of both loops
    }

    echo "This will not be printed\n";
}
?>

				
			

Output:

				
					Outer Loop
Inner Loop