Jump to content

each() function is deprecated... how can I convert the each in this code please... stuck!

Go to solution Solved by Barand,

Recommended Posts


$dir = opendir($dir_name);
$basename = basename($dir_name);
$fileArr = array();

while ($file_name = readdir($dir)){
if (preg_match("/\.jpg$/i", $file_name)) {

#Get file modification date...
$fName = "$dir_name/$file_name";
$fTime = filemtime($fName);
$fileArr[$file_name] = $fTime;
# Use arsort to get most recent first
# and asort to get oldest first

////$numberOfFiles = sizeOf($fileArr);
$numberOfFiles =7;
$thisFile = each($fileArr);
$thisName = $thisFile[0];
$thisTime = $thisFile[1];
$thisTime = date("d M y", $thisTime);



closedir ($dir);

this returns the latest 7 files in a dir... works fine but each is now deprecated so gives warning

Link to post
Share on other sites
  • Solution

Best way to traverse an array is with foreach().

$fileArr = [];
$files = glob("$masterdir/*.jpg");
foreach ($files as $fname) {
    $t = filemtime($fname);
    $fileArr{$fname} = $t;
foreach (array_slice($fileArr, 0, 7) as $thisName => $thisTime) {                // iterate through first 7 files
    echo "$thisName &mdash; " . date("d M y", $thisTime) . '<br>';


  • Great Answer 1
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.