
Understanding PHP Control Structures: Conditional and Iterative Logic
Conditional Logic in PHP
PHP uses if, else, and else if (or elseif) statements to perform conditional logic. These statements evaluate expressions and execute different blocks of code based on whether those expressions return true or false.
Basic if Statement
$temperature = 75;
if ($temperature > 80) {
echo "It's a hot day!";
}if...else Statement
$temperature = 65;
if ($temperature > 80) {
echo "It's a hot day!";
} else {
echo "It's a cool day.";
}if...elseif...else Statement
$score = 75;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} else {
echo "Grade: C or below";
}Best Practice: Use consistent indentation and braces for clarity, even when a single line follows a condition.
Switch Statement
The switch statement is an alternative to multiple if...elseif statements. It evaluates an expression and matches it against several possible values.
$day = date('l');
switch ($day) {
case 'Monday':
echo "It's the start of the work week.";
break;
case 'Friday':
echo "Time to celebrate the weekend!";
break;
default:
echo "It's just another day.";
}Note: Always include abreakafter each case to avoid fall-through behavior. Use thedefaultcase to handle unexpected values.
Iterative Logic in PHP
Loops are essential for repeating a block of code multiple times. PHP supports several loop types, including for, foreach, while, and do...while.
for Loop
The for loop is ideal when you know the number of iterations in advance.
for ($i = 0; $i < 10; $i++) {
echo "Iteration $i\n";
}foreach Loop
The foreach loop is used to iterate over arrays and objects. It is the most commonly used loop in PHP for array manipulation.
$fruits = ['apple', 'banana', 'orange'];
foreach ($fruits as $fruit) {
echo "I like $fruit.\n";
}while and do...while Loops
Use while when the number of iterations is not known in advance. The do...while loop guarantees at least one execution.
$count = 0;
while ($count < 5) {
echo "Count is $count\n";
$count++;
}
do {
echo "This runs at least once.\n";
} while (false);Combining Conditions and Loops
Real-world scenarios often require combining control structures. For instance, validating user input or filtering data from an array.
$numbers = [12, 45, 7, 32, 9, 28];
foreach ($numbers as $num) {
if ($num % 2 == 0) {
echo "$num is even.\n";
} else {
echo "$num is odd.\n";
}
}Best Practices
| Practice | Description |
|---|---|
| Use braces with all conditions | Enhances readability and prevents logic errors. |
| Avoid deep nesting | Refactor complex logic into functions or use early returns. |
Use === for strict comparison | Prevents unexpected type juggling. |
Prefer foreach over for for arrays | More readable and less error-prone. |
| Limit loop complexity | Break complex loops into smaller, reusable functions. |
