Performance of array_shift()

When the array size is large, the performance of array_shift() will become poor. Let’s see the following example:

$a = range(0, 100000);

$ts = microtime(true);
for ($i=0; $i<100000; $i++) $tmp = array_shift($a); printf("array_shift=%.4f\n", microtime(true) - $ts);

Result:

array_shift=200.3999

It took 200 seconds which is totally unacceptable. Therefore, if you need to run array_shift() inside a loop, I would suggest doing that in another way. For example:

$a = range(0, 100000);

$pos = 0;
function shift($array) {
return $array[$pos++];
}

$ts = microtime(true);
for ($i=0; $i<100000; $i++) $tmp = shift($a); printf("shift=%.4f\n", microtime(true) - $ts);

Result:

shift=0.2817