开发者

get previous array values in foreach

My array :

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

then i do a foreach

foreach($arr as $ar){
  echo $ar;
}

that will output jan to des

my question is how do i display the previous values in current key?

F开发者_JAVA百科or example, when I get to feb, I want to display jan too, when I get to jul, i want to display jun, etc.


$previousValue = null;
foreach($arr as $ar){
  echo $ar;
  if($previousValue) {
    echo $previousValue;
  }
  $previousValue = $ar;
}


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';


reset($array);
while($val=current($array))
{
    var_dump($val); // current
    var_dump(prev($array)); // previous
    next($array); // back to current
    next($array); // next
}


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 />';
    }
}


for ( $i = 0; $i <count($arr); $i++) {
    echo $arr[$i]
    if($i > 0){
     echo $arr[$i-1]
   }
}


foreach($arr as $key => $value){
  if ($key > 0) {
   echo $arr[$key-1];
  }
  echo $value;
}

See this question and answer.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜