Brandon Williams
Brandon Williams

Reputation: 79

PHP - Display 4 most recent images from directory

Very new to PHP. I have sucessfully got this piece of code working to display 4 images from a directory, however it shows the first 4 images by name (001.png, 002.png, 003.png and 004.png) which are the lowest numbers and happen to be the least recently uploaded:

<?php
$pictures = glob("directory/*.png"); 
for( $i=0; $i<=3; $i++ ){ 
echo "<img src=\"".$pictures[$i]."\" />"; 
}  
?>

I am looking to change that to get the 4 most recently uploaded in a directory by name. In other words, I would like to display the last 4 images with the highest number. I have tried this below however I am getting Parse error: syntax error, unexpected T_VARIABLE on line 4

<?php
$pictures = glob("directory/*.png"); 
$no_pictures = count($pictures)-1 
$limit = $no_pictures-3 
for( $i = $no_pictures; $i >= $limit; $i--; ){ 
echo "<img src=\"".$pictures[$i]."\" />\n"; 
}  
?>

Any help is appreciated. Thanks for your time.

Upvotes: 2

Views: 1952

Answers (1)

Sean
Sean

Reputation: 12433

You are missing the ending semicolons ; on lines 3 & 4 [edit] AND you have an extra one in your for loop after $i-- -

<?php
$pictures = glob("directory/*.png"); 
$no_pictures = count($pictures)-1;  // was missing ;
$limit = $no_pictures-3;            // was missing ;
for( $i = $no_pictures; $i >= $limit; $i--){  // removed ; after $i--
echo "<img src=\"".$pictures[$i]."\" />\n"; 
}  
?>

Upvotes: 1

Related Questions