PHP natcasesort给出了booleon错误

问题描述:

I have been trying to read the errors and figure out the solution for a while now, I can't seem to get it.

In short, the code below grabs a numbered list of php files that displays the events. However, when there are no php files in this directory, it displays the text, Sorry, No upcoming events.

$events = glob("$_SERVER[DOCUMENT_ROOT]/assets/events/shot/*.php");

if(count($events)) {
natcasesort($events);

$i=0;
foreach($events as $event) {
if($i > 3) {
    break;
}
$event = basename($event);
include("$_SERVER[DOCUMENT_ROOT]/assets/events/shot/$event");
$i++;
};
    }

else {

echo 'Sorry, no upcoming events.';

}

My problem is, when there are no php files in the directory, I get the errors:

Warning: natcasesort() expects parameter 1 to be array, boolean given in /home/famili23/public_html/assets/events/shot.php on line 11

Warning: Invalid argument supplied for foreach() in /home/famili23/public_html/assets/events/shot.php on line 14

I cannot quite figure this one out. If someone can help me on this, thank you!!

glob may return false on error (I'm not sure which circumstances would constitute an error). false cast to an array will be the value array(false), i.e. an array with one entry false. count casts its argument to an array, so in the event of glob returning false, count(false) will result in 1. That's why it's entering the condition regardless, and since $events is not an array the following functions are complaining.

Since an empty array is equal to false, I'd suggest you simply do this:

if ($events) ...

This is true if and only if glob returned an array with at least one element, and false in all other cases including empty arrays and false.