DommyCastles
DommyCastles

Reputation: 425

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!

Upvotes: 2

Views: 7559

Answers (6)

user2409529
user2409529

Reputation: 21

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

Upvotes: 2

Xavier Castillo
Xavier Castillo

Reputation: 1

$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>";
}

Upvotes: 0

KiaiFighter
KiaiFighter

Reputation: 667

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--;
}

Upvotes: 0

Ahmed Muhammad
Ahmed Muhammad

Reputation: 118

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

Upvotes: 2

Junaid
Junaid

Reputation: 2094

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

Upvotes: 0

Sampson
Sampson

Reputation: 268414

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.

Upvotes: 6

Related Questions