Created
October 10, 2011 09:05
-
-
Save dundee/1274919 to your computer and use it in GitHub Desktop.
Foreach vs array_reduce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$arr = array( | |
array('a', '1'), | |
array('b', '2'), | |
); | |
// klasicky | |
$out = array(); | |
foreach ($arr as $v) { | |
$out[$v[0]] = $v[1]; | |
} | |
// funkcionalne | |
$out2 = array_reduce($arr, function($out2, $v) { | |
$out2[$v[0]] = $v[1]; | |
return $out2; | |
}); | |
echo ($out === $out2) . "\n"; | |
print_r($out); | |
print_r($out2); | |
/* vystup: | |
1 | |
Array | |
( | |
[a] => 1 | |
[b] => 2 | |
) | |
Array | |
( | |
[a] => 1 | |
[b] => 2 | |
) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment