Search code examples
phparrayssplitoverlap

Create 2-element rows from flat array where the every second row value is also the first value of the next row


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

How can I achieve the following output....

output:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

[1] => Array
    (
        [0] => b
        [1] => c
    )

[2] => Array
    (
        [0] => c
        [1] => d
    )

[3] => Array
    (
        [0] => d
        [1] => e
    )

[4] => Array
    (
        [0] => e
    )

)


Solution

  • You can use this, live demo here.

    <?php
    $arrayinput = array("a","b","c","d","e");
    
    $array = [];
    foreach($arrayinput as $v)
    {
      $arr = [];
      $arr[] = $v;
      if($next = next($arrayinput))
        $arr[] = $next;
      $array[] = $arr;
    }
    print_r($array);