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.
$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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With