how to flatmap in php

The flatMap() function is not natively available in PHP, but it can be implemented using a combination of array_map() and array_merge() functions.

Here's an example implementation of flatMap():

main.php
function flatMap(array $array, callable $callback): array {
    return array_merge(...array_map($callback, $array));
}
119 chars
4 lines

This implementation takes an input array and a callback function as arguments. The callback function should transform each element of the input array into an array of zero or more elements. The array_map() function is used to apply the callback function to each element of the input array. The resulting array of arrays is flattened using the array_merge() function, which combines all the arrays into a single array.

Here's an example usage of flatMap():

main.php
$array = [1, 2, 3];
$callback = function($num) {
    return [$num, $num * 2];
};
$result = flatMap($array, $callback);
print_r($result);
// Output: Array ( [0] => 1 [1] => 2 [2] => 2 [3] => 4 [4] => 3 [5] => 6 )
212 chars
8 lines

In this example, the input array is [1, 2, 3]. The callback function doubles each element and returns an array of two elements. The resulting array of arrays is flattened into a single array, which is then printed to the console.

gistlibby LogSnag