Split array into two arrays by index even or odd

前端 未结 10 2073
执笔经年
执笔经年 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 12:43

    I am not sure if this is the most elegant way, but it should work a charm:

    $odd=array();
    $even=array();
    $count=1;
    foreach($array as $val)
    {
        if($count%2==1)
        {
            $odd[]=$val;
        }
        else
        {
            $even[]=$val;
        }
        $count++;
    }
    

提交回复
热议问题