5 tips to make your PHP code beautiful (1)

Posted at 4:18 pm in php

Get your brackets right

..and indent your code properly, always. Always give to each of your curly brackets their very own line.
I am taking a snippet from Kohana to demonstrate this.

(bad) What do you think of this code ?

if ( ! is_array($data)){
if (strpos($data, '[') !== FALSE)
{$data = preg_replace('/\[.*\]/', '', $data);
}$data = empty($data) ? array() : array('for' => $data);}

(not nice) This is much better

if ( ! is_array($data)){
	if (strpos($data, '[') !== FALSE){
		$data = preg_replace('/\[.*\]/', '', $data);
	}
	$data = empty($data) ? array() : array('for' => $data);
}

(sweet) A nicely formatted code should show like this. You can tell at a glance where your every if begins and ends.

if ( ! is_array( $data) )
{
	if ( strpos( $data, '[') !== FALSE )
	{
		$data = preg_replace('/\[.*\]/', '', $data );
	}
	$data = empty( $data ) ? array() : array( 'for' => $data );
}
 

Written by Stefano Forenza on April 20th, 2008

Leave a Reply