My array :
$arr = array(\"jan\",\"feb\",\"mar\",\"apr\",\"mei\",\"jun\",\"jul\",\"agu\",\"sep\",\"okt\",\"nov\",\"des\");
then i do a foreach<
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';
foreach($arr as $key => $value){
if ($key > 0) {
echo $arr[$key-1];
}
echo $value;
}
See this question and answer.
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 />';
}
}
reset($array);
while($val=current($array))
{
var_dump($val); // current
var_dump(prev($array)); // previous
next($array); // back to current
next($array); // next
}
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;
}
$previousValue = null;
foreach($arr as $ar){
echo $ar;
if($previousValue) {
echo $previousValue;
}
$previousValue = $ar;
}