Last active
May 3, 2024 21:29
-
-
Save davidrjonas/8f820ab0c75534b45189eba1d1fbeb23 to your computer and use it in GitHub Desktop.
Simple flatmap() or mapcat() for PHP 7
This file contains hidden or 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 | |
/** | |
* 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)); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
empty($array) === true
will createPHP 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.