-1

I'm confusing :S with this script...This script working if there are some file, and I will get the echo like:

|test1.txt|test2.txt|test3.txt|test4.txt

the problem is when doesn't exist any file, the php will get an error:

Warning: asort() expects parameter 1 to be array, null given in htdocs\test\ReadFolder8.php on line 6

Warning: Invalid argument supplied for foreach() in htdocs\test\ReadFolder8.php on line 8

is possible to make a function who look if there are the file, if not, get an echo like "no file found" without error?

<?php
    $User = $_GET['User'];

    foreach (glob("Myuser/$User/*.txt") as $path) { 
        $docs[$path] = filectime($path);
    } asort($docs); // sort by value, preserving keys

    foreach ($docs as $path => $timestamp) {
        //print date("d M. Y:|H:i:s |", $timestamp);
        print '|'. basename($path) .'' . "" . '';

    }
?>

the last thing, I don't understand how works the order for the data creation of file... if I create a new file, the new file will the last of the string...how I can invert the order??

Thank you very much :)

2 Answers 2

2

The solution is simple: You need to initialize your variable $docs before you use it to an empty variable like this:

$docs = array(); // <-- create array $docs before use...

foreach (glob("Myuser/$User/*.txt") as $path) { 
    $docs[$path] = filectime($path);
}
asort($docs); // sort by value, preserving keys

To let the function output an error message instead, if there are no such files, you can simply count the number of array elements using count($docs) and check if it is 0 like this:

if (count($docs) == 0) {
    echo "no file found";
}
3
  • Added some code/explanation for the error-case handling.
    – SDwarfs
    Oct 31, 2014 at 13:23
  • 1
    You can of course also use if (!file_exists(glob("Myuser/$User/"))) { .... error ... } to check if the directory exists. Note that file_exists() also works for directories.
    – SDwarfs
    Oct 31, 2014 at 13:25
  • Thanks!! it's working perfect!! the last question is...How order the file by date? the newest file it's the last... thanks again!!
    – Ribi
    Oct 31, 2014 at 13:32
0

You can use arsort() instead of asort() to get the latest file as first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.