get previous array values in foreach

后端 未结 7 1435
死守一世寂寞
死守一世寂寞 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:32

    foreach ($arr as $key => $ar) {
        //check we aren't on jan (otherwise we get $key = -1 which doesn't work)
        if ($key != 0) {
            //print previous month followed by current month
            echo $arr[$key - 1] . '-' . $ar . '
    '; } } //OR, if you want to be able to roll through years then: $last_key = end(array_keys($arr)); foreach ($arr as $key => $ar) { //check we aren't on jan if ($key != 0) { //print previous month followed by current month echo $arr[$key - 1] . ' - ' . $ar . '
    '; } else { echo $arr[$last_key] . ' - ' . $ar . '
    '; } }

提交回复
热议问题