phparraysduplicatesinterleave

How to interleavedly duplicate an array in php?


For instance, I have an array:

$x = array("a", "b", "c", "d", "e");

Is there any function to iterate all values of array and duplicate the values into:

$x = array("a", "a", "b", "b", "c", "c", "d", "d", "e", "e");

I've not found any related solution after googled it for a while.

Thanks so much!


Solution

  • Looks like a reasonably simple reduction (using array_reduce())

    $x = array_reduce($x, function($arr, $val) {
        array_push($arr, $val, $val);
        return $arr;
    }, []);
    

    Demo ~ https://3v4l.org/eNH8a


    Just realised that "reduction" sounds a bit funny since we're making the array bigger. Think of it more as a transformation. See https://en.wikipedia.org/wiki/Reduce_(parallel_pattern)