5 tips to make your PHP code beautiful (2)

Posted at 4:58 pm in php

Thoughtful minimalism

Think about the most concise, clear and readable way to write the code your writing. Assume you were writing a function to get a file extension (.gif, .doc, etc.). You could be tempted to use string manipulation functions.

$filename = 'file.doc';
$dot_position = strpos( $filename, '.' );
if ( $dot_position !== false )
{
	$extension = substr( $filename, $dot_position + 1  );
}
var_dump($extension)

It’s a lot of code for such a simple task. Beside that, files with multiple dots ( filename.with.dots.html ) won’t be handled properly.

$filename = 'file.doc';
$extension = array_pop ( explode( '.', $filename ) );
var_dump($extension)

The lesson here is to restlessy try to find the best solutions , even when you thought you knew how to accomplish the task. The one-liner above, is more easy to read and much less error-prone. It will work with file with multiple dots or with no extension without any problem. (note: you may want to filter $filename with basename() to avoid directory names dot to interfere).

I am gonna give another example - imagine you’re trying to print a different string for a bunch of pages on you’re site.

if ( $page_id == 32 || $page_id == 10 || $page_id == null )
{
	echo 'inactive';
} else {
	echo 'active';
}

While this code is pretty ok, you could note that $page_id is repeated one time for every page you want to set as inactive.

$inactive_pages = array( 32, 10, null );
if ( in_array( $page_id, $inactive_pages ) )
{
	echo 'inactive';
} else {
	echo 'active';
}

This way you can add exceptions just inserting a new element in $inactive_pages array. This will make easier refactor the code to read $inactive_pages from a configuration file or from a database.
In situations where you need to keep your code even smaller you could even write a one-liner (but don’t exceed with them, as many people find them less readable - and often they’re right):

echo in_array( $page_id, array( 32, 10, null )  )  ? 'inactive' : 'active';
 

Written by Stefano Forenza on April 20th, 2008

One Response to '5 tips to make your PHP code beautiful (2)'

Subscribe to comments with RSS or TrackBack to '5 tips to make your PHP code beautiful (2)'.

  1. felix | 14 May 08 at 11:09 pm

    $ext = end(explode(’.', $filename));
    just less verbose

Leave a Reply