duandu1915 2016-08-17 19:42 采纳率: 100%
浏览 470
已采纳

PHP检查数组值是否为true

I would like to know what is the appropriate method to check for true in an array key without throwing PHP notices if it doesn't exist?

My script goes through several if statements within a for each loop, and as it goes along, it creates keys in an array called "audit".

So for one iteration of the loop, the array might look like this:

$audit = 
  Array
  (
    'price_changed' => 1,
    'price_changed_to' => 10,
    'quantity_changed' => 1,
    'quantity_changed_to' => 6
  )

For the next, it could look like this:

$audit = 
  Array
  (
    'quantity_changed' => 1,
    'quantity_changed_to' => 4,
    'description_changed' => 1,
    'description_changed_to' => 'Test product'
  )

Now I want to be able to do something like this:

if($audit['price_changed']){
   .... do something ....
}

However in the case of the second item in the for each, this key doesn't exist, and my debug log fills up with PHP notices.

I'm sure I could do something like this below, but it seems like I shouldn't have to type that much for something simple like this.

if(isset($audit['price_changed'])) {
   if($audit['price_changed']) {
     .... do something ....
   }
 }

Am I thinking about this too hard or what?

Edit: this is a slimmed down example of my audit array... too many possibilities to assign zeros to all of them at the start of the loop.

  • 写回答

4条回答 默认 最新

  • droxlzcgnr639823 2016-08-17 19:56
    关注

    Use empty() function. It will check both condtions

    • your key exists in array
    • value of the key is not false or 0 or empty string

    Example:

    if (!empty($audit['price_changed'])) {
        // do something
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)