get previous array values in foreach

后端 未结 7 1433
死守一世寂寞
死守一世寂寞 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';
    
    0 讨论(0)
  • 2021-02-01 23:30
    foreach($arr as $key => $value){
      if ($key > 0) {
       echo $arr[$key-1];
      }
      echo $value;
    }
    

    See this question and answer.

    0 讨论(0)
  • 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 . '<br />';
        }
    }
    
    //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 . '<br />';
        } else {
            echo $arr[$last_key] . ' - ' . $ar . '<br />';
        }
    }
    
    0 讨论(0)
  • 2021-02-01 23:36
    reset($array);
    while($val=current($array))
    {
        var_dump($val); // current
        var_dump(prev($array)); // previous
        next($array); // back to current
        next($array); // next
    }
    
    0 讨论(0)
  • 2021-02-01 23:38

    A little more Dynamic

    $arr  = array(
        "jan",
        "feb",
        "mar",
        "apr",
        "mei",
        "jun",
        "jul",
        "agu",
        "sep",
        "okt",
        "nov",
        "des"
    );
    $arr2 = $arr;
    foreach ($arr as $k => $currVal) {
        unset($arr2[$k]);
        foreach ($arr2 as $k => $v) {
            $nextVal = $v;
    
            break;
        }
        echo "next val: " . $nextVal;
        echo "current val: " . $currVal;
    }
    
    0 讨论(0)
  • 2021-02-01 23:42
    $previousValue = null;
    foreach($arr as $ar){
      echo $ar;
      if($previousValue) {
        echo $previousValue;
      }
      $previousValue = $ar;
    }
    
    0 讨论(0)
提交回复
热议问题