Control Structures in PHP: Conditional Statements and Loops

Olivia J
8 min readMay 23, 2023

--

PHP is a powerful and flexible scripting language for web development. It allows you to create dynamic and interactive web pages with ease. In this blog post, we will explore some of the essential concepts of PHP, such as control structures.

Photo by Ben Griffiths on Unsplash

What are control structures in PHP?

Control structures are core features of the PHP language that allow your script to respond differently to different inputs or situations. This could allow your script to give different responses based on user input, file contents, or some other data. The following flowchart explains how a control structure works in PHP:

There are two main types of control structures in PHP: conditional statements and loops.

What are conditional statements in PHP?

Conditional statements allow you to branch the path of execution in a script based on whether a single or multiple conditions evaluate to true or false. Put simply, they let you test things and perform various actions based on the results.

There are four types of conditional statements in PHP: if, if-else, if-elseif-else, and switch.

If statement

The if statement is the simplest form of conditional statement. It executes a block of code only if a specified condition is true. The syntax of the if statement is:

if (condition) {
// code to be executed if condition is true
}

The condition can be any expression that evaluates to a boolean value (true or false). The code block can be a single statement or multiple statements enclosed in curly braces.

For example:

$x = 10;
if ($x > 0) {
echo "$x is a positive number.";
}

The above code will print “$x is a positive number.” only if the value of $x is greater than zero.

If-else statement

The if-else statement is an extension of the if statement. It executes one block of code if a specified condition is true, and another block of code if the condition is false. The syntax of the if-else statement is:

if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}

For example:

$x = -5;
if ($x > 0) {
echo "$x is a positive number.";
} else {
echo "$x is a negative number.";
}

The above code will print “$x is a negative number.” because the value of $x is less than zero.

If-elseif-else statement

The if-elseif-else statement is a further extension of the if-else statement. It allows you to test multiple conditions and execute different blocks of code accordingly. The syntax of the if-elseif-else statement is:

if (condition1) {
// code to be executed if condition1 is true
} elseif (condition2) {
// code to be executed if condition2 is true
} elseif (condition3) {
// code to be executed if condition3 is true
} ...
else {
// code to be executed if none of the conditions are true
}

You can have as many elseif clauses as you want, but only one else clause at the end. The conditions are evaluated from top to bottom, and only the first one that evaluates to true will execute its corresponding block of code. If none of the conditions are true, the else block will execute.

For example:

$grade = 85;
if ($grade >= 90) {
echo "You got an A.";
} elseif ($grade >= 80) {
echo "You got a B.";
} elseif ($grade >= 70) {
echo "You got a C.";
} elseif ($grade >= 60) {
echo "You got a D.";
} else {
echo "You got an F.";
}

The above code will print “You got a B.” because the value of $grade is between 80 and 90.

Switch statement

The switch statement is an alternative way of writing multiple if-elseif-else statements. It compares a given expression with several possible values and executes the corresponding block of code. The syntax of the switch statement is:

switch (expression) {
case value1:
// code to be executed if expression matches value1
break;
case value2:
// code to be executed if expression matches value2
break;
case value3:
// code to be executed if expression matches value3
break;
...
default:
// code to be executed if expression doesn't match any value
}

The expression can be any value or variable that can be compared with the case values. The case values can be any constant or literal value. The break statement is used to end each case block and prevent the execution from falling through to the next case. The default block is optional and executes only if none of the case values match the expression.

For example:

$day = "Monday";
switch ($day) {
case "Monday":
echo "Today is Monday.";
break;
case "Tuesday":
echo "Today is Tuesday.";
break;
case "Wednesday":
echo "Today is Wednesday.";
break;
case "Thursday":
echo "Today is Thursday.";
break;
case "Friday":
echo "Today is Friday.";
break;
case "Saturday":
echo "Today is Saturday.";
break;
case "Sunday":
echo "Today is Sunday.";
break;
default:
echo "Invalid day.";
}

The above code will print “Today is Monday.” because the value of $day matches the first case value.

What are loops in PHP?

Loops are control structures that allow you to repeat a block of code multiple times until a certain condition is met. Loops are useful for performing repetitive tasks, such as iterating over arrays, processing user input, generating output, etc.

There are four types of loops in PHP: while, do-while, for, and foreach.

While loop

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

while (condition) {
// code to be executed repeatedly while condition is true
}

The condition can be any expression that evaluates to a boolean value (true or false). The code block can be a single statement or multiple statements enclosed in curly braces.

For example:

$x = 1;
while ($x <= 10) {
echo "$x ";
$x++;
}

The above code will print “1 2 3 4 5 6 7 8 9 10” because the value of $x starts from 1 and increments by 1 until it reaches 10.

Do-while loop

The do-while loop executes a block of code once and then repeats it as long as a specified condition is true. The syntax of the do-while loop is:

do {
// code to be executed at least once and repeatedly while condition is true
} while (condition);

The difference between the do-while loop and the while loop is that the do-while loop checks the condition at the end of each iteration, whereas the while loop checks it at the beginning. This means that the do-while loop will always execute at least once, even if the condition is false from the start.

For example:

$x = 11;
do {
echo "$x ";
$x++;
} while ($x <= 10);

The above code will print “11” because the value of $x starts from 11 and does not satisfy the condition, but still executes once before checking it.

For loop

The for loop executes a block of code for a specified number of times. The syntax of the for loop is:

for (initialization; condition; increment) {
// code to be executed for each iteration while condition is true
}

The initialization expression sets up the initial state of the loop, such as declaring and initializing a counter variable. The condition expression tests whether the loop should continue or not, usually by comparing the counter variable with a limit value. The increment expression updates the state of the loop after each iteration, usually by increasing or decreasing the counter variable.

For example:

for ($x = 1; $x <= 10; $x++) {
echo "$x ";
}

The above code will print “1 2 3 4 5 6 7 8 9 10” because it sets up $x as a counter variable starting from 1 and ending at 10, increasing by 1 after each iteration.

Foreach loop

The foreach loop executes a block of code for each element in an array or an object. The syntax of the foreach loop for arrays is:

foreach (array as $value) {
// code to be executed for each element in array using $value variable
}

The array can be any variable that holds an array value. The $value variable holds the current element in the array during each iteration. You can use the $value variable to access or modify the element in the code block.

For example:

$colors = array("red", "green", "blue");
foreach ($colors as $color) {
echo "$color ";
}

The above code will print “red green blue” because it loops through each element in the $colors array and assigns it to the $color variable.

The syntax of the foreach loop for associative arrays is:

foreach (array as $key => $value) {
// code to be executed for each element in array using $key and $value variables
}

The array can be any variable that holds an associative array value. The $key variable holds the current key in the array, and the $value variable holds the current value associated with that key. You can use both variables to access or modify the element in the code block.

For example:

$scores = array("Alice" => 90, "Bob" => 80, "Charlie" => 70);
foreach ($scores as $name => $score) {
echo "$name scored $score. ";
}

The above code will print “Alice scored 90. Bob scored 80. Charlie scored 70.” because it loops through each key-value pair in the $scores array and assigns them to the $name and $score variables.

The syntax of the foreach loop for objects is:

foreach (object as $property => $value) {
// code to be executed for each property in object using $property and $value variables
}

The object can be any variable that holds an object value. The $property variable holds the current property name in the object, and the $value variable holds the current value of that property. You can use both variables to access or modify the property in the code block.

For example:

class Car {
public $color;
public $model;

public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
}

$myCar = new Car("red", "Toyota");
foreach ($myCar as $property => $value) {
echo "$property: $value ";
}

The above code will print “color: red model: Toyota” because it loops through each property in the $myCar object and assigns them to the $property and $value variables.

In this blog post, we have learned about some of the essential concepts of PHP, such as control structures. We have seen how to use conditional statements and loops to control the flow of execution in a script based on different conditions and situations.

Control structures are vital for writing any PHP script that involves logic and decision making. By understanding these concepts, you can write more efficient and flexible code that can handle different kinds of scenarios.

I hope you found this blog post helpful and informative. If you have any questions or feedback, please feel free to leave them in the comments section below.

Happy coding! 😊

--

--