Reducing Script Size for PHP Golf Contests

Many of our past blog posts have focused on best-practices and creating usable, maintainable code. But when you're doing contests like PHP Golf, you want to minimize the amount of code used to accomplish a task. This post will demonstrate tips on reducing the size of your scripts. While the "advice" is ideal for such contests, please also consider this article a "what-not-to-do-when-developing-web-applications" peice :)

1. Take advantage of deprecated functions

Several challenges involve converting data between string and array form. Functions like "explode" and "implode" are perfect for this. But before you use them, check out "join" and "split" - these work almost the same way, but will save you a couple extra bytes.

2. Omit spaces before keywords

Some keywords, like 'echo', will work fine if you omit the trailing space:

// So instead of:
echo $foo;
// you can do:
echo$foo;
// This also works:
echo"hi";

Although this only saves you one byte, this can easily add up to a few bytes. This technique can be used with other keywords like 'as':

for($a as$b)

I haven't tried this with other keywords, though I would expect similar results.

3. Take full advantage of Order of Operations on related variables

In one of the challenges, I need to do add and multiply some variables and then provide the output. I was able to chain everything together into one statement. Here are a couple examples of this in action:

// Find element with index $j * $n + $i, incrementing $j for later use; return the result
echo$s[$j++*$n+$i];
// Another example:
// Set $k equal to $l for later use; find the element with that index in the array and increment it
if($s[$k=$l]++)return 1;

Take advantage of the fact that assignments happen right-to-left, and that $i++ increments $i AFTER the statement executes, whereas ++$i increments it while/before execution.

4. Fully utilize the 'condition' part of 'for' loops

'for' loops take on the following syntax:

for(initializer; condition; incrementOperation)

Because 'condition' is executed on each loop, we can stuff our logic into there instead:

// Instead of this:
for($i = 0; $i < $n; $i++ )
{
	$n=count($s=explode(' ',$x));
	// do other stuff
}
// We can cram everything into the for's condition:
for(;$i<$n=count($s=explode(' ',$x));$i++)
{
	// do other stuff
}

This works well if your loop is modifying a variable which is checked later in the condition. In the example above, we save 2 bytes by not mentioning variable $n twice.

Bonus tip: Did you notice I also removed the initializer? Instead of setting $i to 0, we let PHP figure out that $i will be used as a number - and undefined numbers will resolve to 0. We saved at least 4 bytes there.

5. Displaying a static string plus a variable

Some of the PHP Golf challenges require a newline after each result. We can optimize it like so:

// Original statment (15 bytes):
echo $a . "\n";
// Remove spaces between stuff (reduced by 3 bytes):
echo$a."\n";
// Remove the concatenation operator (reduced by 1 byte):
echo"$a\n";
// Replace the newline escape character with a literal newline.
// Note this optimization only works if using Unix-style EOLs to save your PHP script
echo"$a
";
// Final count: 10 bytes

6. Use different functions creatively

The creative or uncommon use of some functions can drastically reduce the size of your script. Here are some examples I've used in the past:

// Remove empty elements from an array without needing to loop through
// the elements and manually unset them:
$newarr = array_filter($oldarr);

// Replace all single quotes with double quotes, and all spaces with dashes:
$newstr = strtr($oldstr,"' ",'"-');

7. Where possible, use functions that return a useful value

It's possible (and very helpful) to string together multiple functions as parameters of each other, which drastically cuts down on file size. Experiment with similar functions that return slightly different values to see which one gives you the most functionality with the least number of characters.

Sometimes you need to use functions like 'sort' to sort an array. Be careful though, because sort() doesn't return a value, so you can't chain it!

Conclusion

Challenges like PHP Golf are a great way to test your knowledge of a language and learn more about it. You'll discover how the internals of the language works, what assumptions it makes, as well as new functions and new ways to use old ones. But like I mentioned earlier, these techniques can be very helpful when solving PHP Golf problems but should always be avoided when writing production code.

Do you have any other tips to cut down on the size of your scripts? Share them in the comments!

Tags

PHP

About the Author

Colin O'Dell first started programming on an old Apple II-e at the age of 7. Within four years, he mastered several BASIC variants and sold his first commercial application. After tinkering with different languages and technologies for a few...

 
blog rss banner
 

View All

Testimonials

"Unleashed Technologies has done a phenomenal job with two different major and ongoing projects.

Director of Marketing, Recruiting Firm

Mike and his team have taken over a web site that was limping along, with an extensive list of problems and a weak design.  They jumped into the task and are rapidly disposing of issues that had...

Laura Perry, Marketing Director
Whiteford | Taylor | Preston