August 29th, 2011 at 9:57 pm

First or last element of an array in PHP

I’ve seen horrible things today. Somebody (the file didn’t carry an author … good for him or her) tried to get the first element of a PHP array – using array_shift. Of course, array_shift modifies the source array, so he worked on a copy of his original array, as (of course) he didn’t want to alter the array itself. Looked something like this:

$copyOfArray = $array;
$firstElementOfArray = array_shift($copyOfArray);

That is obviously a waste of memory and CPU cycles. Usually not noticable, of course. But with large arrays or when frequently executed, it will add stress to the system.

There’s a very “cheap” way to get the first value of any given array. The reset function does just that. (end returns the last element.)

$firstElementOfArray = reset($array);

Now, reset will set the internal array pointer to the first value. However, unless your doing crazy things or writing sloppy code, you shouldn’t care about that anyway.