Reputation: 714
I have the following code to search the folder /images/ for images and echo them. However, it displays the images from a random order everytime I refresh the page. The images are named 1, 2, 3, 4 and so on. Any way to make it so that the last number (ex: 4) is the first one being displayed and so on?
<?php
$dirname = "images";
$images = scandir($dirname);
shuffle($images);
$ignore = Array(".", "..");
foreach($images as $curimg){
if(!in_array($curimg, $ignore)) {
echo "<img src=\"". $dirname . '/' . $curimg ."\">" ;
}
}
?>
Thanks in advance.
Upvotes: 1
Views: 1518
Reputation: 5524
This is due to your shuffle. You are randomizing your array. Let me introduce you to: http://php.net/manual/en/function.array-reverse.php which is
<?php
$dirname = "images";
$images = scandir($dirname);
$images = arsort(array_reverse($images, true));
$ignore = Array(".", "..");
foreach($images as $curimg){
if(!in_array($curimg, $ignore)) {
echo "<img src=\"". $dirname . '/' . $curimg ."\">" ;
}
}
?>
Update:
$dirname = "Images";
$images = scandir($dirname);
sort($images,SORT_NUMERIC);
krsort($images);
$ignore = Array(".", "..");
foreach($images as $curimg){
if(!in_array($curimg, $ignore)) {
echo "<img src=\"". $dirname . '/' . $curimg ."\"> \n" ;
}
}
What I have been working with:
Without the sort();
and krsort();
i return:
<img src="Images/1.png">
<img src="Images/10.png">
<img src="Images/11.png">
<img src="Images/2.png">
<img src="Images/3.png">
<img src="Images/4.png">
<img src="Images/5.png">
<img src="Images/6.png">
<img src="Images/7.png">
<img src="Images/8.png">
<img src="Images/9.png">
With the krsort and sort.. I return:
<img src="Images/11.png">
<img src="Images/10.png">
<img src="Images/9.png">
<img src="Images/8.png">
<img src="Images/7.png">
<img src="Images/6.png">
<img src="Images/5.png">
<img src="Images/4.png">
<img src="Images/3.png">
<img src="Images/2.png">
<img src="Images/1.png">
Which I presume is what you are looking for.
Upvotes: 3
Reputation: 544
<?php
$dirname = "images";
$files = scandir($dirname, 1); // using SCANDIR_SORT_DESCENDING PHP 5.4+ ONLY!
foreach ($files as $file) {
if ($file !== '.' && $file !== '..') {
echo "<img src=\"". $dirname . '/' . $file ."\">" ;
}
}
?>
Upvotes: 0
Reputation: 1979
You could try to load image names into array, than sort array and then echo image tags
Upvotes: 0
Reputation: 23777
http://www.php.net/manual/en/function.array-reverse.php
should be the right function instead of shuffle
UPDATE:
Better would be to sort it directly via scandir:
$images = scandir($dirname, SCANDIR_SORT_DESCENDING);
Upvotes: 1