I wrote the following code in order to find the newest files added in three different folders. I have stored the directories of the folders in an array called path. I also store the names of the newest files in another array.
$path[0] = "/Applications/MAMP/htdocs/php_test/check";
$path[1] = "/Applications/MAMP/htdocs/php_test/check2";
$path[2] = "/Applications/MAMP/htdocs/php_test/check3";
for ($i=0; $i<=2; $i++){
$path_last = $path[$i]; // set the path
$latest_ctime = 0;
$latest_filename = '';
$d = dir($path_last);
while (false !== ($entry = $d->read())) {
$filepath = "{$path_last}/{$entry}";
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
$array[$i] = $latest_filename ; // assign the names of the latest files in an array.
}
}
Everything works fine but now I try to put the same code in a function and call it in my main script. I use this code in order to call it:
include 'last_file.php'; // Include the function last_file
$last_file = last_file(); // assign to the function a variable and call the function
I am not sure if this is correct. What I want to do is to return the array in my main script .. I hope it's clear here what I am trying to explain. Thanks D.
This is the last_file function:
function last_file(){
for ($i=0; $i<=2; $i++){
$path_last = $path[$i]; // set the path
$latest_ctime = 0;
$latest_filename = '';
$d = dir($path_last);
while (false !== ($entry = $d->read())) {
$filepath = "{$path_last}/{$entry}";
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
$array[$i] = $latest_filename ; // assign the names of the latest files in an array.
}
}
return $array;
}//end loop
}//end function
return $array;assuming$arrayis the one you wish to return.return $array;outside the loop, before the function's closing}