Dariel Pratama
Dariel Pratama

Reputation: 1675

Iterate array from the end without reverse

Let's say I have the following array in PHP:

$a = ['2015-10-10'=>'30', '2015-11-11'=>'100'];

How do I iterate through the array from the end without reversing it first. I want to check and change all of the values based on conditions.

Upvotes: 0

Views: 66

Answers (2)

Vigneswaran S
Vigneswaran S

Reputation: 2094

the above answer will results an error if one of the array's values is false or NULL or 0 , try this you will get an new idea

<?php
$a = array('2015-10-10'=>'30', '2015-11-11'=>'100', '2015-14-11'=>'105');
$im=implode(',', $a);// make as a string 
$newarr=explode(',',$im);// convert it as an array with 0-3 as a index
$size=sizeof($newarr);
$size=sizeof($newarr);
for($j=$size;$j>=0;$j--){// reverse loop
echo $newarr[$j]."<br>";
}
//print_r($newarr);
//print_r($im);
?>

Upvotes: 0

Ali Zia
Ali Zia

Reputation: 3875

You can try this.

$new_array=end($a);

do {
    // Your Code here
}
while ($new_array=prev($a));

Upvotes: 2

Related Questions