Tiaw Tiaw - 4 months ago 12
PHP Question

return all images in array from latest added

I want to make an array that return every images from a folder from the latest added to the first one.

So, create an array it's ok, get the time of each image added it's ok,
sort images from latest to first it's ok.

For the moment I only can get the latest image added, but I don't know how can I create a while that will show all my images?

This is my code:

<?php
$tabFich = array();
$allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
$iterator = new DirectoryIterator("../img/peinture/");

foreach ($iterator as $fileinfo) {
if ($fileinfo->isFile()) {
if (!$fileinfo->isFile() || !in_array($fileinfo->getExtension(), $allowedExtensions))
continue;
$tabFich[$fileinfo->getCTime()] = $fileinfo->getFilename();
}
}

ksort($tabFich);
$lastFile = end($tabFich);
?>

<div class="vs-peint" style="background:url(../img/peinture/<?php echo $lastFile; ?>)"></div>

Answer

Try something like this and let me know if it works for you

$tabFich = array();
$allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
$iterator = new DirectoryIterator("../img/peinture/");

foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile()) {

        if (!$fileinfo->isFile() || !in_array($fileinfo->getExtension(), $allowedExtensions))
            continue;

        array_push($tabFich, array("file_datetime" => $fileinfo->getCTime(), "file_name" => $fileinfo->getFilename()));
    }
}

usort($tabFich, function($a, $b) {
    return $a['file_datetime'] - $b['file_datetime'];
});

foreach ($tabFich as $key => $value) {?>

    <div class="vs-peint" style="background:url('../img/peinture/<?php echo $value['file_name']; ?>'); height: 400px; width: 400px;"></div>

<?php }
Comments