5 Built-In PHP Shortcuts to Optimize Your Code

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

A way to quickly define a range of values (alpha or numeric) without having to type out the entire array.

// 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

I don’t use this one as much anymore aside from the example below to separate out someones full name.

// cluttered...
$sp = $split(' ', $name, 2);
$first_name = $sp[0];
$last_name = $sp[1];

// nice and clean
list($first_name, $last_name) = split(' ', $name, 2);

5. switch() Statement

Common statement that I’m sure most of use 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!

1 Comment

Leave a Comment

Please complete all required fields