PHP has several control structures that allow you to control the flow of your code based on certain conditions. Here are some examples of common control structures in PHP:
if statement
The if
statement allows you to execute a block of code if a condition is true.
$x = 10;
if ($x > 5) {
echo "x is greater than 5";
}
You can also use the else
keyword to specify a block of code to be executed if the condition is false.
$x = 10;
if ($x > 5) {
echo "x is greater than 5";
} else {
echo "x is not greater than 5";
}
You can also use the elseif
keyword to specify additional conditions to be checked.
$x = 10;
if ($x > 15) {
echo "x is greater than 15";
} elseif ($x > 5) {
echo "x is greater than 5 but not greater than 15";
} else {
echo "x is not greater than 5";
}
switch statement
The switch
statement allows you to execute a block of code based on the value of a variable.
$x = "apple";
switch ($x) {
case "apple":
echo "x is an apple";
break;
case "banana":
echo "x is a banana";
break;
case "orange":
echo "x is an orange";
break;
default:
echo "x is something else";
}
while loop
The while
loop allows you to execute a block of code repeatedly as long as a condition is true.
$x = 0;
while ($x < 5) {
echo "x is $x\n";
$x++;
}
do while loop
The do while
loop is similar to the while
loop, but the block of code is executed at least once before the condition is checked.
$x = 0;
do {
echo "x is $x\n";
$x++;
} while ($x < 5);
for loop
The for
loop allows you to execute a block of code a specified number of times.
for ($x = 0; $x < 5; $x++) {
echo "x is $x\n";
}
These are just a few examples of the control structures available in PHP. You can use these structures to create more complex programs and logic.