Using array_filter, atleast to me, was thought as an optimisation method to create faster array filtering. But I ran a simple bench mark on the data I was filtering and saw it did no such thing.
Result:
array_filter -> function found in 0.00402585482597
foreach -> function found in 0.0044710290432
foreach found in 0.00203925895691
As you can see it doubled the result set's time. But this is by 2 milliseconds, so only take this with a grain of sand and not as a bucket of howto. What this really comes down to is what do you see is more maintainable, then whats more reuseable, and lastly which ever you like best.
array_filter vs foreach certainly makes it look cleaner but its offset by a function you then have to find, to see what is areally going on. Even more so that function is pronounced in a string, making it hard to visually see what its doing. The whole point of array_filter is getting your logic into a function to better maintain it when it grows. But you can just as well do that by still using foreach with the function. This is much more apparent and makes it easier on IDE's to understand that your really doing, as well as other, who are new to php.
<?php
$rows = array(/* ... */); // long array data here
$limit = 1000;
// TEST 1
$avg = 0;
function filter_by_category($row)
{
if(strtolower($row['category']) === 'armed forces bowl')
{
return true;
}
else
{
return false;
}
}
for ($i = 0 ; $i < $limit ; $i++)
{
$t = microtime(true);
$results = array();
$results = array_filter($rows, 'filter_by_category');
$avg += microtime(true) - $t;
}
echo 'array_filter -> function found in ', $avg / $limit, '<br />';
// TEST 2
$avg = 0;
for ($i = 0 ; $i < $limit ; $i++)
{
$t = microtime(true);
$results = array();
foreach($rows as $row)
{
if(filter_by_category($row))
{
$results []= $row;
}
}
$avg += microtime(true) - $t;
}
echo 'foreach -> function found in ', $avg / $limit, '<br />';
// TEST 3
$avg = 0;
for ($i = 0 ; $i < $limit ; $i++)
{
$t = microtime(true);
$results = array();
foreach($rows as $row)
{
if(strtolower($row['category']) === 'armed forces bowl')
{
$results []= $row;
}
}
$avg += microtime(true) - $t;
}
echo 'foreach found in ', $avg / $limit, '<br />';
?>
« Back to my notebook