Decompose array so every 2nd element is in a different array

So I would like to take an "unsorted" array and get every second element out of the "unsorted" array and put it into a new array, so what's left is two arrays.

$unsorted = array("present","Bob","late","Jessie","late","Carl","present","Jessica","absent","Adam","present","Hope");

I thought of creating a for loop, but I couldn't find any functions to create the two arrays.

Any help would be greatly appreciated, thanks!

2 answers

  • answered 2019-04-21 08:37 u_mulder

    Simple, but need some understanding:

    $unsorted = array("present","Bob","late","Jessie","late","Carl","present","Jessica","absent","Adam","present","Hope");
    $sorted = array_map(null, ...array_chunk($unsorted, 2));
    print_r($sorted);
    

  • answered 2019-04-21 08:40 Eddie

    One option is using the classic foreach loop.

    $unsorted = array("present","Bob","late","Jessie","late","Carl","present","Jessica","absent","Adam","present","Hope");
    
    $array1 = array();
    $array2 = array();
    foreach( $unsorted as $key => $val ) {
        if ( $key % 2 ) $array2[] = $val;
        else $array1[] =  $val;
    }
    

    $array1 will result to:

    Array
    (
        [0] => present
        [1] => late
        [2] => late
        [3] => present
        [4] => absent
        [5] => present
    )
    

    $array2 will result to:

    Array
    (
        [0] => Bob
        [1] => Jessie
        [2] => Carl
        [3] => Jessica
        [4] => Adam
        [5] => Hope
    )