...

/

Bracket and Parenthetic Spacing

Bracket and Parenthetic Spacing

In this lesson will look at how to use parenthesis and braces in PHP.

In general, parenthesis and brackets should not use any additional spaces. The exception is that space should always follow PHP control structures that accept arguments with parenthesis (declare, do-while, elseif, for, foreach, if, switch, while), to help distinguish them from functions and increase readability.

Example 1: Incorrect

$arr[ $foo ] = 'foo';

Example 1: Correct

$arr[$foo] = 'foo'; // no spaces around array keys

Example 2: Incorrect

function foo ( $bar )
{
}

Example 2: Correct

function foo($bar) // no spaces around parenthesis in function declarations
{
}

Example 3: Incorrect

foreach( $query->result() as $row )

Example 3: Correct

foreach ($query->result() as $row) // single space following PHP control structures, but not in interior parenthesis