PHP semantics – the array push

When code is always written the way that it’s written, it sometimes takes an outsider voice to question the rote.

PHP has strong array support, that’s a given. PHP also has a lot of legacy clutter, and no versed PHP developer will tell you otherwise. That’s ok – you work with the good API and ignore that bad ones.

Consider pushing a value onto an array. PHP provides the array_push( $array, $value ) function. However, there is a native mechanism for this built into the very language; even the PHP documentation suggests that this is more appropriate for pushing single values as no function call overhead is incurred.

So it’s quite a common scenario to build up some array, usually in a loop, as such:


foreach( $data as $elem )
 $array[] = $elem[ 'some_property' ];

and this feels quite natural and familiar, using the native syntax of appending the empty square brackets to the variable and then assigning some value. Natural and familiar to one experienced with PHP, yes. Today, one of my coworkers who is not a PHP developer voiced his puzzlement over the syntax. While assigning to an index as such $array[ 5 ] = 'value'; makes sense even coming from other language backgrounds, is assigning to an empty index obvious as to the intent? “Oh yes, of course. It’s always done like this in PHP…” yes but is it intuitive as to the result or at least as to the type of expression? Note that in other languages this kind of syntax is usually intended for initializing an array.

As an advocate for self-documenting code and embedded semantics, this kind of critique lead me to question and reconsider native array pushes. Primarily, the intent of this expression isn’t so much of an assignment to a special type of variable but an application of an operator to some structure. Unfortunately, arrays aren’t native objects so there’s no hope of a crystal clear method call but PHP does offer an overloaded array operator for taking the union of two arrays. Perhaps there is a way to leverage that approach of symbolic operators. To my surprise and delight, it turns out that there is – PHP will allow the array push syntax to be written as a combined operator (I have trouble visualizing how a standalone [] operator would fit nicely with existing PHP grammar).

And here’s the magic, shifting a single whitespace character to greatly improve the readability. $array []= 'value'; While perhaps not necessarily obvious as to what specifically is being done, is at least clear in that some operation is being applied to $array that involves the string ‘value’.