Skip to content

Instantly share code, notes, and snippets.

@Kcko
Forked from dundee/gist:1274919
Created May 3, 2019 19:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kcko/397eb5cc0209dd8f52a07ba97593d28e to your computer and use it in GitHub Desktop.
Save Kcko/397eb5cc0209dd8f52a07ba97593d28e 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