PHP's array_shift Performance

< 1 minute read

PHP’s array_shift is a relatively slow way to fetch the first item from an array; it’s much better to use reset. For example,

$first_item = array_shift($arr); // slower
$first_item = array_shift($arr); // faster

array_shift() modifies the original array and can be pretty slow because it needs to completely reindex the array (remove first element then shuffle everything else forward by one “slot”), so unless you specifically need to continue to work with the array after removing the first element, it is far far more performant to use reset() which simply rewinds the array pointer to the beginning then returns the first element.

Even reversing the array, using array_reverse() followed by array_pop() to remove and return the last element (the element previously known as the first element) is faster than using array_shift(). Results are likely different in newer versions of PHP, but in this article they removed 1000 elements from a 100,000 element array, with the following results:

array_pop takes 0.00089 seconds
array_shift takes 15.15544 seconds
array_reverse + array_pop takes 0.03934 seconds

I realize most of us will never be dealing with arrays that large and the result may be negligible for most code, but it doesn’t hurt to know what you are working with.

This content is entirely from our lead developer, Brent Christensen, internal code review… I just thought it was such a good point that the world needed to know!

Leave a Reply