Today, I came across code that looks something like this:
$this->batchedIds[$id] = $item;
$this->batchedItems[] = $item;
My immediate reaction was that it was assignment. Of course, I was wrong and Chesterton’sfence wins again.
So TIL that there are two common ways of appending to an array in PHP:
-
$array[] =: single element only -
array_push(): supports multiple elements- Note: There are a number of other
array_*methods likearray_merge().
- Note: There are a number of other
When should I use one over the other?
For single values, $array[] = is slightly faster since it aovids the overhead of
a function call. The arraypush doc also notes:
Note: If you use arraypush() to add one element to the array, it’s better to use
$array[] =because in that way there is no overhead of calling a function.
For multiple values, array_push() can be clearer and more convenient than
repeating multiple append statements.
In practice, the performance difference is negligible in most code and only becomes relevant in tight loops or very large datasets.
My takeaway is not to mix styles. Both forms are valid, so pick one approach and use it consistently throughout a codebase to reduce cognitive overhead and keep intent obvious.