0

I use foreach to show items from mysql table, but it lists first items first. I want to list last items first. The code:

foreach ( $result as $print )   { 
 $print->sender_user;
 $print->reciever_user;
 $print->content;
}

I mean that if I add a new item to mysql table this code should show it above the other items.
But it shows first added item last.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

2

Simple, use array_reverse

http://php.net/manual/en/function.array-reverse.php

array_reverse — Return an array with elements in reverse order

$result = array_reverse($result);

foreach ( $result as $print )   { 
     $print->sender_user;
     $print->reciever_user;
     $print->content;
}

Otherwise if it's numerically indexed you can always use for

$len = count($result)-1;

for($i=$len; $i>=0; --$i){
   $row = $result[$i];
}

And my favorite

$result = [1,2,3,4];

$row = end($result);
do{
   echo $row."\n";
}while($row = prev($result));

Try it here

https://3v4l.org/NINss

And with just while, you cant do prev in the while condition because you lose the last element of the array, so it's a bit lamer.

$result = [1,2,3,4];

$row = end($result);
while($row = current($result)){
    echo $row."\n";

    prev($result);
}

https://3v4l.org/No1Rb

I think that is about it, I could probably do one with goto but that would be showing off.

ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38