How can I put the following array value in the current key array

What is the best way to create an array (with unordered indexes) using the following index value in the current index. I tried using next () but didn't help. I mean:

Array
(
    [0] => a
    [8] => b
    [2] => c
    [7] => d
    [9] => e
    [11] => f
)

therefore, I want this data to be an array like below.

Array
(
    [0] => Array
    (
        [current] => a
        [next] => b
    )
    [8] => Array
    (
        [current] => b
        [next] => c
    )
    [2] => Array
    (
        [current] => c
        [next] => d
    )
    [7] => Array
    (
        [current] => d
        [next] => e
    )
    [9] => Array
    (
        [current] => e
        [next] => f
    )
    [11] => Array
    (
        [current] => f
        [next] => 
    )
)

what could be the fastest way to do this.

+4
source share
2 answers

UPDATE

For an unordered array

$newarray = array();
$length = count($oldarray);
for($i = 0; $i < $length ; ++$i)
{
   $newarray[] = array('current'=>current($oldarray),'next'=>next($oldarray));
}
0
source

Note: this solution actually works as proven. This was underestimated for some unclear reason.

, , , , ( )

<?php
// simulate the array
$arr = [0=>'a',8=>'b',2=>'c',7=>'d',9=>'e',11=>'f'];

// iterate it without messing with its internal pointer
for($i=0;$i<count($arr);$i++)
    $arr[key($arr)] = ["current" => current($arr), "next" => next($arr)];

// test it
echo '<pre>';
print_r($arr);

OUTPUT

Array
(
    [0] => Array
        (
            [current] => a
            [next] => b
        )

    [8] => Array
        (
            [current] => b
            [next] => c
        )

    [2] => Array
        (
            [current] => c
            [next] => d
        )

    [7] => Array
        (
            [current] => d
            [next] => e
        )

    [9] => Array
        (
            [current] => e
            [next] => f
        )

    [11] => Array
        (
            [current] => f
            [next] => 
        )

)

- current(), next() key(), .

+2

Source: https://habr.com/ru/post/1612748/


All Articles