Skip to content

Instantly share code, notes, and snippets.

@dundee
Created October 10, 2011 09:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dundee/1274919 to your computer and use it in GitHub Desktop.
Save dundee/1274919 to your computer and use it in GitHub Desktop.
Foreach vs array_reduce
<?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