get previous array values in foreach

后端 未结 7 1440
死守一世寂寞
死守一世寂寞 2021-02-01 23:04

My array :

$arr = array(\"jan\",\"feb\",\"mar\",\"apr\",\"mei\",\"jun\",\"jul\",\"agu\",\"sep\",\"okt\",\"nov\",\"des\");

then i do a foreach<

7条回答
  •  粉色の甜心
    2021-02-01 23:28

    You can use the keys to get the previous key.

    foreach($arr as $key => $ar){
        $prev = $arr[$key-1];
        echo  "previous value -" .$prev;
    }
    

    You also have prev() as an internal array pointer:

    $transport = array('foot', 'bike', 'car', 'plane');
    $mode = current($transport); // $mode = 'foot';
    $mode = next($transport);    // $mode = 'bike';
    $mode = next($transport);    // $mode = 'car';
    $mode = prev($transport);    // $mode = 'bike';
    $mode = end($transport);     // $mode = 'plane';
    

提交回复
热议问题