dri98076 2014-05-19 10:11
浏览 22
已采纳

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!!

  • 写回答

1条回答 默认 最新

  • doujun7161 2014-05-19 11:02
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏