Control Structures

These include if, for, while, switch, etc. Here is an example if statement, since it is the most complicated of them:

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

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.

For switch statements:

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

case 
2:
    
action2;
    break;

default:
    
defaultaction;
    break;
}
?>

Split long if statements onto several lines

Long if statements may be split onto several lines when the character/line limit would be exceeded. The conditions have to be positioned onto the following line, and indented 4 characters. The logical operators (&&, ||, etc.) should be at the beginning of the line to make it easier to comment (and exclude) the condition. The closing parenthesis and opening brace get their own line at the end of the conditions.

Keeping the operators at the beginning of the line has two advantages: It is trivial to comment out a particular line during development while keeping syntactically correct code (except of course the first line). Further is the logic kept at the front where it's not forgotten. Scanning such conditions is very easy since they are aligned below each other.

<?php

if (($condition1
    
|| $condition2)
    && 
$condition3
    
&& $condition4
) {
    
//code here
}
?>

The first condition may be aligned to the others.

<?php

if (   $condition1
    
|| $condition2
    
|| $condition3
) {
    
//code here
}
?>

The best case is of course when the line does not need to be split. When the if clause is really long enough to be split, it might be better to simplify it. In such cases, you could express conditions as variables an compare them in the if() condition. This has the benefit of "naming" and splitting the condition sets into smaller, better understandable chunks:

<?php

$is_foo 
= ($condition1 || $condition2);
$is_bar = ($condition3 && $condtion4);
if (
$is_foo && $is_bar) {
    
// ....
}
?>

There were suggestions to indent the parantheses "groups" by 1 space for each grouping. This is too hard to achieve in your coding flow, since your tab key always produces 4 spaces. Indenting the if clauses would take too much finetuning.

Ternary operators

The same rule as for if clauses also applies for the ternary operator: It may be split onto several lines, keeping the question mark and the colon at the front.

<?php

$a 
$condition1 && $condition2
    
$foo $bar;

$b $condition3 && $condition4
    
$foo_man_this_is_too_long_what_should_i_do
    
$bar;
?>