PHP Pitfalls Part 2 – Code Blocks

In PHP blocks may stand on their own line. For this reason if you take the following code:


public function foo()
{
$array = array( 1, 2, 3 );
$copy = array();
for( ; $value = current( $array ); next( $array ) );
{
array_push( $copy, $value );
}
print_r( $copy );
}

And run it you will get an array like this:
Array( 0 => bool(false) )

Why is this? Take a look at the line with the for loop, see the semicolon at the end? PHP basically evaluates $value to equal false and then runs the array_push line only one time. Not that you would intentionally put a semicolon at the end of the loop but stuff happens.

This entry was posted in PHP. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>