Control Structures in PHP
Control structures are essential for controlling the flow of execution in your PHP code. They allow you to make decisions and repeat actions based on conditions.
If Statements
The if
statement is used to execute code based on a condition.
- Basic If Statement:
if ($condition) {
// Code to be executed if the condition is true
}
- If-Else Statement:
if ($condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
- If-Else If-Else Statement:
if ($condition1) {
// Code to be executed if the first condition is true
} elseif ($condition2) {
// Code to be executed if the second condition is true
} else {
// Code to be executed if none of the conditions are true
}
Switch Statements
The switch
statement is used to execute one block of code out of many based on the value of a variable.
- Switch Statement:
switch ($variable) {
case 'value1':
// Code to be executed if $variable equals 'value1'
break;
case 'value2':
// Code to be executed if $variable equals 'value2'
break;
default:
// Code to be executed if $variable does not match any case
}
Loops
Loops are used to execute a block of code repeatedly.
- For Loop:
for ($i = 0; $i < 10; $i++) {
// Code to be executed on each iteration
}
- While Loop:
while ($condition) {
// Code to be executed while the condition is true
}
- Do-While Loop:
do {
// Code to be executed at least once and then repeatedly while the condition is true
} while ($condition);
Break and Continue Statements
The break
and continue
statements are used to control the flow within loops.
- Break Statement:
The break
statement is used to exit from a loop or switch
statement prematurely.
while ($condition) {
if ($someCondition) {
break; // Exit the loop
}
// Code to be executed
}
- Continue Statement:
The continue
statement skips the remaining code inside the loop for the current iteration and proceeds to the next iteration.
for ($i = 0; $i < 10; $i++) {
if ($i % 2 == 0) {
continue; // Skip even numbers
}
// Code to be executed for odd numbers
}
These control structures provide the necessary tools to build logic and handle various scenarios in your PHP applications.