PHP snippet: creating arrays
Posted by Neil on 14th June 2007
Arrays are usually created with the array() construct. It takes an arbitrary number of arguments and returns them in an array. Simple enough.
The other less common way of creating an array consisting of a single value is to use a typecast.
$t = 1; $a = (array)$t;
This code casts $t to an array and is equivalent to using $t = 1; $a = array($t). The only difference is where you put the parentheses.
Actually, that's not the only difference. Using the typecast is about 10%-12% slower than the array constructor so it can make a difference inside tight loops.
What did we learn?
If you need to create an array from a single variable, use the array() constructor and don't bother with a cast.
