Home Indentation and Spacing in PHP

Indentation

Spacing and indentation should be consistent throughout your code. Many developers choose to use 4-space or 2-space indentation.

You may choose to start your top-level indentation of your PHP code within the <?php ... ?>, as long as you are consistent.

<?php

  echo "Hello!";

  ?>
<?php

  echo "Hello!";

?>
<?php

echo "Hello!";

?>

In PHP, each nested statement (e.g., a statement following a "{" brace) should be indented exactly once more than the previous line's indentation.

Here are some examples of bad indentation in PHP:

function foo() {
$x = 2;
print($x);
}

  function bar() {
print(1);
  }

Here are some examples of good indentation in PHP:

function foo() {
  $x = 2;
  print($x);
}

function bar() {
  print(1);
}

Line Formatting

Line Breaks

Opening "{" brackets should be on the same line as the function/loop/conditional header, and corresponding closing "}" brackets should be on their own line and indented to align with the indentation of the line that has the corresponding opening "{".

Here are some examples of bad line breaks in PHP:

function foo() { $x = 2; print($x);}

function bar()
{
  $y = 2;
  print($y);
}

Here are some examples of good line breaks in PHP:

function foo() {
  $x = 2;
  print($x);
}

function bar() {
  $y = 2
  print($y);
}

Long Lines

Lines should never be longer than 100 characters in PHP, and many developers aim at 80 characters as the line character limit. When any line is longer than 100 characters, break it into two lines by pressing Enter after an operator and reindenting the line. Indent the trailing second part of the line such that it aligns with the first letter of the first word following the opening "=" above if one exists (for variable assignments), otherwise aligned with the character following the opening "(" on the previous line.

Here are some examples of bad reindentation of long lines:

$result = reallyLongFunctionOne() + reallyLongFunctionTwo() +
reallyLongFunctionThree() + reallyLongFunctionFour();

$result2 = reallyLongFunction($parameterOne, $parameterTwo, 
$parameterThree, $parameterFour);

Here are some examples of good reindentation of long lines:

$result = reallyLongFunctionOne() + reallyLongFunctionTwo() +
          reallyLongFunctionThree() + reallyLongFunctionFour();

$result2 = reallyLongFunction($parameterOne, $parameterTwo, 
                              $parameterThree, $parameterFour);

Blank Lines

Place a blank line between the end of each PHP function and the start of the next function's function comment. You should not have more than one blank line in a row.

function foo() {
  $x = 2;
  print($x);
}
function bar() {
  print("hi");
}
// Prints 2 
function foo() {
  $x = 2;
  print($x);
}

// Prints "hi"
function bar() {
  print("hi");
}

Spacing

Spacing in Expressions

Place a space between operators, assigments ("=") and their operands.

$x=($a+$b)*$c/$d+foo();
$x = ($a + $b) * $c / $d + foo();