Skip to content

Instantly share code, notes, and snippets.

@davidrjonas
Last active May 3, 2024 21:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidrjonas/8f820ab0c75534b45189eba1d1fbeb23 to your computer and use it in GitHub Desktop.
Save davidrjonas/8f820ab0c75534b45189eba1d1fbeb23 to your computer and use it in GitHub Desktop.
Simple flatmap() or mapcat() for PHP 7
<?php
/**
* If you need something safer or more complete see https://github.com/lstrojny/functional-php,
* in particular, https://github.com/lstrojny/functional-php/blob/master/src/Functional/FlatMap.php
*
* @param Callable $fn Mapping function that returns an array
* @param array $array Data over which $fn will be mapped
* @return array
*/
function flatmap(callable $fn, $array)
{
return array_merge(...array_map($fn, $array));
}
@veeeeeeeeeee
Copy link

empty($array) === true will create
PHP Warning: array_merge() expects at least 1 parameter, 0 given in ...

due to the fact that splat (...) of empty array evaluates to nothing.

return array_merge([], ...array_map($fn, $array)); will return [], if this is a more desirable behaviour.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment