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;
?>
Indenting and Line Length (Previous) Function Calls (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:

Note by: StanE
Curly braces can be written on the same line, but only for very short statements (normally for single lines):

if ($a == b) {
doSomething();
}
else {
doSomethingElse();
}

This is ok, because the developer sees instantly where the condition starts and where it ends. But this should not be done with lot of lines, especially if they don't fit on the screen. Then it is better to put them in the same "column". Many editors (especially scintilla based) draw a vertical line between the opening and closing brace when you position the cursor caret at the brace so you instantly and visually see, where it begins and where it ends (without even looking at the braces themself). Placing the opening curly brace in the same line on longer statements, will break this useful feature in some editors, some will not allow you to collapse / expand the statement. And even if not and the vertical line is drawn, it will be abruptly stopped at the beginning and it looks like your code is broken. Also, it is harder to see where a statement begins. I really don't understand this argument. For multiple checks in a condition with && and || operators you (correctly) say to put the operators at the front, so they can be seen instantly instead somewhere at the end. But at the same time you say that the opening curly brace should be put at the end of the same row. Because of the vertical-draw-line feature for curly braces in many editors, you should write braces for case conditions in switch statements too. This will draw the nice vertical line and it will allow you to collapse / expand the case conditions too! I never seen an editor which can collapse case conditions without braces (at least not in the editors / IDEs I use).
Note by: Pistachio
The documentation says "You are strongly encouraged to always use curly braces even in situations where they are technically optional." But then proceeds to list a switch statement contrary to that statement. So the statement should withdrawn or the example should be modified as follows:

switch(condition) {
case 1:{
action;
break;
}
...
}
Note by: hipertracker
Original PEAR standards for control structures are OK. I hate wasting screen space for nasty constructs like

switch ($x)
{
case

...

if even worse (used in CodeIgniter)

if ()
{
...
}
else
{
...
}

That looks like shit. PHP is already ugly anough, don't make it worse.
Note by: temhawk
I don't use PEAR, and I am an unexperienced programer, but I think coding standards, for the purpose of both readability/understandability and reliability, are important.

I wanted to add that I find it much easier to read an if-statement, when there is an empty line above the condition.

e.g. (random code taken out of my current project)

date_default_timezone_set("Europe/Dublin");
$logFile = (@include_once "config.php") == true ? LOG_FILE : $_SERVER["DOCUMENT_ROOT"] . "/error_log.txt";

if ($fh = @fopen($logFile, "a"))
{
fwrite($fh, date("c") . "\n" . strip_tags($errorMsg) . "\n\n");
fclose($fh);
}

In combination with the two curly braces on their own lines, it makes the condition stand out more, and easier to spot such a logical struture in a file with much code.
Note by: acmpires@sapo.pt
I think that the "if" control structure is more readable this way:

if ($condition1) {
// some code
}
elseif ($condition2) {
// more code here
}
else {
// a bit more code
}
Note by: bobvandell@hotmail.com
I'm with Maga on this one. That's how I've been doing it for years.
Indent from the case so that the case it's self stands out.
Note by: blackid
My strong belief is still that this would add a nice way to represent loops...

switch (condition)
{
case 1;
action 1;
break1;

case 2;
action 2;
break2;
}

This makes the system much more readable and easy to understand. Every indent specifies a child. and two indents is especially useful when you are reading about 100 lines of code. It truely helps!
Note by: Maga
I think that better is:

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

    case 
2:
        
action2;
        break;

    default:
        
defaultaction;
        break;
}
Indentation+Brakes
?>
Note by: wiesemann
Phil, the indentation like in your example (i.e. with 4 spaces for the "case" statements) is also accepted in the PEAR coding standards.
Note by: phil@signalz.com
I would have expected more indentation, like this
<?php
switch (condition) {
    case 
1:
        
action1;
        break;

    case 
2:
        
action2;
        break;

    default:
        
defaultaction;
        break;
}
?>


Note by: dpn12@comcast.net
Might you consider adding to your current K&R format, below

...
switch (condition) {
case 1:
action1;
break;

case 2:
action2;
break;

}
...


/**/

...
switch (condition)
{
case 1:
action1;
break;

case 2:
action2;
break;
}
...


this above format that some believe to be more readable?