J. Doe J. Doe - 5 months ago 14
PHP Question

How to make foreach loop print out higher number first PHP

I have a code that works perfect for me with one exception. I have 2 folders called "1" and "2". Within Folder "1" I have 3 pictures called "image1.jpg" "image2.jpg" and "image3.jpg"

The scenario now is that it prints folder "1" before "2" and it prints out "image1.jpg" before "image2.jpg"

Is it possible by a small edit without adding excessive or code that takes too much calculations to make the selection of the folder + image to the highest number instead of lowest?

Code attached below:

$directory_name = "pics/";
$images = glob($directory_name."*/*.jpg");
foreach($images as $image)
{
echo '<img src="/'.$image.'">';

}

Answer

You could use rsort:

$directory_name = "pics/";
$images = glob($directory_name."*/*.jpg");
rsort($images);
foreach($images as $image) 
{ 
    echo '<img src="/'.$image.'">';

} 
Comments