removing empty elements from array is most likely a very common task for everyday programming. different people work on it differently. some runs N times loop and some other tries by finding offset and then by unsetting that. let me show you some common approach of doing it and possibly the best way too :), needless to say, in a php way – most of the time such a microsecond does not matter, but well, its still good to find out the best solution 🙂
first of all, lets write a function which will create a random array with empty elements
[source lang=’php’]
function generateRandomArray($count=10000)
{
$array = range(0,($count-1));
for($i = 0;$i<1000;$i++)
{
$offset = mt_rand(0,$count);
$array[$offset] = “”;
}
return $array;
}
[/source]
now lets see some different approaches to get it done.
probably most common approach
[source lang=’php’]
$array = generateRandomArray();
$len = count($array);
$start = microtime(true);
for ($i=0;$i< $len;$i++)
{
if(""==$array[$i]) unset($array[$i]);
}
$end = microtime(true);
echo ($end-$start);
[/source]
you can see the output varies from 0.13-0.14 seconds for an array with 10000 elements in a 2.66 ghz core 2duo machine running mac osx 10.5.8 with 4GB ram.
here is another better approach using array_diff()
[source lang='php']
$array = generateRandomArray();
$start= microtime(true);
$empty_elements = array("");
$array = array_diff($array,$empty_elements);
$end = microtime(true);
echo ($end-$start);
[/source]
this one takes 0.052-0.059 seconds and surely is a significant improvement over the last one
here is another improved version using array_filter()
[source lang='php']
$array = generateRandomArray();
$start= microtime(true);
$array = array_filter($array);
$end = microtime(true);
echo ($end-$start);
[/source]
it takes like 0.002 seconds to complete 🙂 - pretty good one, eh? (thanks damdec, for reminding about it)
and this is the last one which was my favorite one using array_keys() taking advantage of the optional search_values parameter 🙂
[source lang='php']
$array = generateRandomArray();
$start= microtime(true);
$empty_elements = array_keys($array,"");
foreach ($empty_elements as $e)
unset($array[$e]);
$end = microtime(true);
echo ($end-$start);
[/source]
this is an amazing improvement over the previous solutions, it takes only around 0.0008 - 0.0009 seconds for an array of 10000 elements.
i hope you enjoyed this post with micro benchmarks 😀 - happy phping