Welcome Guest, Not a member yet? Register   Sign In
foreach versus array_map
#1

[eluser]xwero[/eluser]
With all the php5.3 talk about closures i wondered what would be more readable, a foreach loop or a array_map call to isolate a single field from every row in a database result.
Code:
$ids = array(); foreach($rows as $row){ $ids[] = $row['id']; }
// VERSUS
$ids = array_map(function ($row){ return $row['id']; },$rows);
The foreach code needs a predefined ids variable to set the default result so the array_map function wins.

But then i did a quick performance test using the CI benchmarking class and the result was foreach : 0.0057 and array_map : 0.0318. I have to mention i didn't do the test using php5.3 so i didn't use a closure but the current syntax.
Code:
function get_id($row){ return $row['id']; }

$ids = array_map('get_id',$rows);
Later today i will do a benchmark with php5.3 to see if the closure is faster than the current syntax.
#2

[eluser]Dam1an[/eluser]
I'm suprised the array_map was slower :-S Will be interesting to see the revised results with PHP5.3

I think the foreach loop is more user friendly, as everyone knows about them, whereas only a small subset know about array_map (although it can be very useful when you do know about it)
#3

[eluser]TheFuzzy0ne[/eluser]
I prefer foreach, personally. I think it's more readable - like pseudo code.
#4

[eluser]xwero[/eluser]
In php5.3 RC3 with the same data but another method of measuring, foreach : 0.00048 and array_map with closure : 0.00066.

My conclusion : i'm using array_map in php5.3. The reason why is because with array_map you can't forget to set the default result.




Theme © iAndrew 2016 - Forum software by © MyBB