简体   繁体   中英

Iterate through a foreach loop backwards in PHP

I have here a foreach loop that displays images from a database onto a webpage. What I would like to do is iterate through the foreach loop backwards, so the latest content is shown first on the webpage. Here is my code:

$sql = "SELECT COUNT(*) FROM 'UPLOADPICS'";

    if ($sth = $dbhandle->query($sql)){
        if ($sth->fetchColumn() > 0){
            $sql = "SELECT link FROM 'UPLOADPICS'";
            foreach ($dbhandle->query($sql) as $row){
                $content = $row['link'];
                ?>
                <img src="<?php echo $content ?>" />
                <br/>
                <br/>
                <?php
            }
        }

        else {
            print "No rows matched the query";
        }

Is this possible? Thanks so much in advance!

Rather than looping backwards, you could order your results with ORDER BY to show the most recent items first. This is typically the most common method used.

SELECT foo, bar 
FROM uploadpics 
ORDER BY 
  date DESC

Of course this is more than a mere suggestion; you won't be able to run through the values in reverse anyway without first loading them into a new array collection, and then iterating over that backwards - so you'd be wasting some precious time and resources.

if you don't have a date field in your table .. you can order by id in a Descending order

    $sql = "SELECT link FROM `UPLOADPICS` ORDER BY `id` DESC";

if you don't like that you can use array_reverse() function

<?php
    $a = array('a', 'b', 'c');
    for ($i = count($a) - 1; $i >= 0; --$i) {
        echo $a[$i];
    }
    echo "\n";
 ?>

You could do a count of the array and iterate through it backwards using a simple index variable that decreases by 1 through each iteration.

$arr = $dbhandle->query($sql);
$i = count($arr) - 1;

while ($i >= 0)
{
    $content = $arr[$i]['link'];
    ?>
    <img src="<?php echo $content ?>" />
    <?php
    $i--;
}

well including Order By would be more appropriate but you may not have date field!

using php's array_reverse() function would reverse the array; in your case first reverse the array and then apply foreach.

Hope this helps

$array=array("uno"=>array(1),"pepito"=>array(1),"clase"=>array(1),"a123"=>array(1));
echo 'normal<br>';
foreach($array as $k=>$v){
    echo $k." = ".$v."<br>";
}
echo 'back<br>';
foreach(array_reverse($array) as $k=>$v){
    echo $k." = ".$v."<br>";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM