Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get previous array values in foreach

Tags:

arrays

php

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?

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

like image 740
Henson Avatar asked Nov 10 '10 19:11

Henson


2 Answers

$previousValue = null;
foreach($arr as $ar){
  echo $ar;
  if($previousValue) {
    echo $previousValue;
  }
  $previousValue = $ar;
}
like image 131
Matt Williamson Avatar answered Oct 16 '22 17:10

Matt Williamson


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';
like image 20
Elzo Valugi Avatar answered Oct 16 '22 19:10

Elzo Valugi