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.

Split long assigments onto several lines (Previous) Ternary operators (Next)
Last updated: Sat, 16 Feb 2019 — Download Documentation
Do you think that something on this page is wrong? Please file a bug report.
View this page in:
  • English

User Notes:

There are no user contributed notes for this page.