Skip Navigation
Madison, Wisconsin
Powderkeg Web Design
February 15, 2013

5 Built-In PHP Shortcuts to Help Optimize Your Code

Matt
Matt

Everyone wants to make the neatest code possible, but sometimes things can get out of control and you end up with an illegible mess. Here are a few tricks I use to clean up my code.

1. Ternary If Statements – I use this the most, I would say I use it at least once for any script I write. Very useful for adding classes to multiple elements and specifying the last element in the bunch. Or alternating between even and odd rows.

// cluttered...
if($article_id) {
	echo $article_id;
} else {
	echo $default;
}

// nice and clean
echo $article_id ? $article_id : $default;
echo ++$x % 2 == 0 ? 'even' : 'odd';

2. in_array() Function – Instead of comparing the same variable multiple times, use the in_array() function to shorten up the if statement

// cluttered...
if($article_id == 5 || $article_id == 12 || $article_id == 20 || $article_id == 33) {
	// do something
}

// nice and clean
if(in_array($article_id, array(5, 12, 20, 33)) {
	// do something
}

3. range() Function

// cluttered...
$alpha = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
foreach($alpha as $a) {
	// do something
}

// nice and clean
foreach(range('A', 'Z') as $a) {
	// do something
}

4. list() Function

// cluttered...
$info = array('name', 'email', 'address');
$name = $info['name'];
$email = $info['email'];
$address = $info['address'];

// nice and clean
list($name, $email, $address) = $info;

5. switch() Statement – Common statement that I’m sure most of us are aware of, but still useful to clean up code.

// cluttered...
if($article_id == 5) {
	// do something specific to article #5
} elseif($article_id == 12 || $article_id == 20) {
	// do something specific to article #12 and #20
} elseif($article_id == 33) {
	// do something specific to article #33
} else {
	// do something
}

// nice and clean
switch($article_id) {
	case '5':
		// do something specific to article #5
		break;
	case '12':
	case '20':
		// do something specific to article #12 and #20
		break;
	case '33':
		// do something specific to article #33
		break;
	default:
		// do something
		break;
}

Do you use any of these functions? Have any of your own? Share it!

Matt Engelbregtsen

Matt Engelbregtsen

Technical Account Manager