I’ve got an array where I want to grab the “negative three” element regardless of array length. (If that doesn’t make sense throw out a comment and I’ll clarify).
The obvious way to do it is $arr[count($arr)-4] but this feels clunky.
Is there a quick, elegant way to do this?
UPDATE
Still fiddling, any thoughts regarding this?
array_slice($arr,-4,-3);
The obvious way returns the single value you want in constant time, assuming you have numeric indexes. The array size is known to PHP already, it just jumps to the offset you want and gives you the result.
array_slicedoes many times as much work, comparing the array size to your offset, computing the loop conditions, creating a new array to store the slice, looping over the portion of the existing array, copying the values into the new array, then returning that array to you.http://lxr.php.net/opengrok/xref/PHP_TRUNK/ext/standard/array.c