Next Previous Contents

8. Control Structures

Control statements should have one space between the control keyword and opening parenthesis, to distinguish them from function calls. You are strongly encouraged to always use curly braces even in situations where they are technically optional. Having them increases readability and decreases the likelihood of logic errors being introduced when new lines are added. You should also leave one alone brace in line before else or elseif keyword in if...else statement.

8.1 if...else

<?php
if ((condition1) || (condition2)) {
    action1;
}
elseif ((condition3) && (condition4)) {
    action2;
}
else {
    defaultaction;
}
?>

8.2 switch

<?php
switch (condition) {
    case 1:
        action1;
        break;

    case 2:
        action2;
        break;

    default:
        defaultaction;
        break;
}
?>

8.3 for

<?php
for ($i=0; $i < 10; ++$i) {
    print("{$i}\n");
}
?>

8.4 foreach

<?php
foreach ($arr_items as $i => $item) {
    print("{$i} => {$item}\n");
}
?>

8.5 while

<?php
while (condition) {
    action;
}
?>

8.6 do...while

do {
    action;
} while (condition);


Next Previous Contents