Home > other >  How can I replace two foreach loops to one assignment (mb two array_map functions)?
How can I replace two foreach loops to one assignment (mb two array_map functions)?

Time:04-28

I have two arrays and I want to get the result array where each element is kind of cartesian product of these 2 arrays.
With foreach's it looks like this:

$first = [1, 2, 3];
$second = ["A", "B"];
$res = [];
foreach($first as $num)
  foreach($second as $sym)
    $res[] = "$num $sym"; // the same as $num . " " . $sym

// Now res is ["1 A", "1 B", "2 A", "2 B", "3 A", "3 B"]

How can I get the same result array with array_map? Something like:

$res = array_map(
  fn($num) => array_map(
    fn($sym) => "$num $sym",
    $second
  ),
  $first
);

// Of course it's wrong
// Here res will be [["1 A", "1 B"], ["2 A", "2 B"], ["3 A", "3 B"]]

Mb there are other functions besides array_map. The main thing is $res = ..., means that $res should be assign to something that returns a result array.
Thanks.

CodePudding user response:

If you want response like this ["1 A", "1 B", "2 A", "2 B", "3 A", "3 B"] and use array_map you can do:

$first = [1, 2, 3];
$second = ["A", "B"];
$res = [];

array_map(
    function ($num) use (&$res, $second) {
        array_map(
            function ($sym) use (&$res, $num) {
                $res[] = "$num $sym";
            },
            $second
        );
    },
    $first
);

And more elegant way but less effective in speed performance, because additionally we use array_merge:

$first = [1, 2, 3];
$second = ["A", "B"];

$res = array_merge(...array_map(
    fn($num) => array_map(
        fn($sym) => "$num $sym",
        $second
    ),
    $first
));
  • Related