BENCHMARK:
I redid the benchmark on my own server, as CodePad was giving sporadic results from it's sporadic server load, and it uses an old version of PHP.
Results:
(Target: 100003)
Last Value: 100003
array_filter took 8.4615960121155 seconds
Last Value: 100003
array_flip took 20.312706947327 seconds
Last Value: 100003
array_pop took 6.7329788208008 seconds
The benchmark script is:
$array=array();
for($run=0; $run<100000; $run++)
{
$rand=rand(0,4);
if ($rand===0) $array[]=''; else $array[]=(string)$rand+$run;
}
$save=$array;
echo '(Target: '.end($array).")
";
$time=microtime(true);
for($run=0; $run<1000; $run++)
{
$array=$save;
$array = array_filter($array);
$lastValue = end($array);
}
$time=microtime(true)-$time;
echo "Last Value: $lastValue
";
echo "array_filter took $time seconds
";
unset($array_2);
$time=microtime(true);
for($run=0; $run<1000; $run++)
{
$array=$save;
$array = array_flip($array);
unset($array['']);
$lastValue = array_pop(array_flip($array));
}
$time=microtime(true)-$time;
echo "Last Value: $lastValue
";
echo "array_flip took $time seconds
";
unset($array_2);
$time=microtime(true);
for($run=0; $run<1000; $run++)
{
$array=$save;
$lastValue = array_pop($array);
while($lastValue==='')
{
$lastValue = array_pop($array);
}
}
$time=microtime(true)-$time;
echo "Last Value: $lastValue
";
echo "array_pop took $time seconds
";
The winner is:
function array_last_noempty($array)
{
$lastValue = array_pop($array);
while($lastValue==='')
{
$lastValue = array_pop($array);
}
return $lastValue;
}