Tips for golfing in PHP

Understand how variables and whitespace interact with PHP's language constructs.

In my (admittedly short) time golfing, I have found that PHP's language constructs (e.g. echo, return, for, while, etc) behave in a less-than-intuitive way when interacting with variables and whitespace.

echo$v;, for example, is perfectly valid, as are return$v; and other similar constructs. These small reductions in whitespace can lead to a significant cumulative decrease in length.

Keep in mind, though, that variables before language constructs require a space after, as in the following example:

foreach($a AS$b){}

Because AS is a language construct, a space is not required before the variable $b, but if one were to omit the space before it, resulting in $aAS, this would be parsed as a variable name and lead to a syntax error.


Use strings wisely.

This answer is two-fold. The first part is that when declaring strings, you can utilize PHP's implicit conversion of unknown constants to strings to save space, e.g:

@$s=string;

The @ is necessary to override the warnings this will produce. Overall, you end up with a one-character reduction.

is that sometimes, it may be space effective to set a variable to the name of an often used function. Normally, you might have:

preg_match(..);preg_match(..);

But when golfing, this can be shortened easily to:

@$p=preg_match;$p(..);$p(..);

With only two instances of "preg_match", you're only saving a single character, but the more you use a function, the more space you will save.


You don't always need to write out conditional checks. For example, some frameworks use this at the top of their files to block access:

<?php defined('BASE_PATH')||die('not allowed');

Or in normal functions

$value && run_this();

instead of

if($value) { run_this(); }