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 foreach

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

which will bring jan to des

My question is: how to display previous values ​​in the current key?

For example, when I get to feb, I want to display jan too, when I get to jul, I want to display jun, etc.

+7
arrays php
source share
7 answers
 $previousValue = null; foreach($arr as $ar){ echo $ar; if($previousValue) { echo $previousValue; } $previousValue = $ar; } 
+33
source share

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 a pointer to the internal array:

 $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'; 
+5
source share
 reset($array); while($val=current($array)) { var_dump($val); // current var_dump(prev($array)); // previous next($array); // back to current next($array); // next } 
+1
source share
 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 />'; } } 
+1
source share
 for ( $i = 0; $i <count($arr); $i++) { echo $arr[$i] if($i > 0){ echo $arr[$i-1] } } 
0
source share
 foreach($arr as $key => $value){ if ($key > 0) { echo $arr[$key-1]; } echo $value; } 

See this question and answer .

0
source share

A bit 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
source share

All Articles