dougan4663 2016-09-22 14:31 采纳率: 0%
浏览 40
已采纳

empty()如何使用布尔表达式?

A guy learning PHP sent me some code that has me scratching my head. He's getting $_POST input, putting it in variables, and then:

if( !empty($id && $name && $email) ) {
    //do something
}

My first inclination was that passing multiple variables as an argument would throw an error, but it evaluates successfully. Am I incorrect that empty() should NOT take a boolean expression? Or - if I'm right - why does it work?

  • 写回答

1条回答 默认 最新

  • dongxuanyi3406 2016-09-22 14:45
    关注

    You can pass an expression to empty rather than a variable (since PHP 5.5), but with an expression like that you lose half of the benefit of using empty. empty checks that variables are set as well as evaluating their "truthiness". When you give it an expression like that, the individual variables within the expression are not checked to exist by empty. The expression is just evaluated as a boolean.

    So if you used separate empty checks, you would get the check that the variables exist as well as the check that they are != false

    if(!empty($id) && !empty($name) && !empty($email))
    

    But when you use

    if (!empty($id && $name && $email))
    

    You will still get into the if block if all the variables are set and have non-false values, but you'll get undefined variable notices if any of them are not set. It's basically the same thing as not using empty at all, like this:

    if ($id && $name && $email)
    

    But if your guy is setting these variables from $_POST, they will be set, (if they weren't in $_POST he'd get undefined index warnings at that point) and the empty here is pointless anyway.

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

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看