Split array into two arrays by index even or odd

前端 未结 10 1973
执笔经年
执笔经年 2020-11-30 12:37

I have this array:

$array = array(a, b, c, d, e, f, g);

I want to split it in two arrays depending if the index is even or odd, like this:<

相关标签:
10条回答
  • 2020-11-30 13:08
    $odd = [];
    $even = [];
    while (count($arr)) {
        $odd[] = array_shift($arr);
        $even[] = array_shift($arr);
    }
    
    0 讨论(0)
  • 2020-11-30 13:08

    One more functional solution with array_chunk and array_map. The last line removes empty item from the 2nd array, when size of a source array is odd

    list($odd, $even) = array_map(null, ...array_chunk($ar,2));
    if(count($ar) % 2) array_pop($even);
    
    0 讨论(0)
  • 2020-11-30 13:09

    Just loop though them and check if the key is even or odd:

    $odd = array();
    $even = array();
    foreach( $array as $key => $value ) {
        if( 0 === $key%2) { //Even
            $even[] = $value;
        }
        else {
            $odd[] = $value;
        }
    }
    
    0 讨论(0)
  • 2020-11-30 13:10

    One

    $odd = $even = array();
    for ($i = 0, $l = count($array ); $i < $l;) { // Notice how we increment $i each time we use it below, by two in total
        $even[] = $array[$i++];
        if($i < $l)
        {
           $odd[] = $array[$i++];
        }
    }
    

    Two

    $odd = $even = array();
    foreach (array_chunk($array , 2) as $chunk) {
        $even[] = $chunk[0];
        if(!empty( $chunk[1]))
        {
           $odd[] = $chunk[1];
        }
    }
    
    0 讨论(0)
提交回复
热议问题