简体   繁体   English

PHP检查数组值true

[英]PHP checking for array value 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? 我想知道什么是合适的方法来检查数组键中的true而不抛出PHP通知(如果不存在)?

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". 我的脚本在for循环中遍历了多个if语句,并且随着脚本的进行,它在称为“ 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. 但是,对于每个项的第二项,此键不存在,并且我的调试日志中充满了PHP声明。

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. 编辑:这是我的审计数组的精简示例...在循环开始时,有太多的可能性为所有零分配零。

You can use array_key_exists 您可以使用array_key_exists

if (array_key_exists('price_changed', $audit)) {
 .... do something ....
}

Use empty() function. 使用empty()函数。 It will check both condtions 它将检查两个条件

  • your key exists in array 您的密钥存在于数组中
  • value of the key is not false or 0 or empty string 键的值不能为false0或为empty string

Example: 例:

if (!empty($audit['price_changed'])) {
    // do something
}

Rather than using a nested if you can simply do: 如果可以简单地执行以下操作,而不是使用嵌套:

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

For PHP7, you can use the null coalescing operator, ?? 对于PHP7,您可以使用null合并运算符, ?? :

if ($value['price_changed'] ?? false)

if price_change isn't set, ?? 如果未设置price_change,则?? will return the second arg instead, causing the if to fail, since the expression would evaluate to false: 将返回第二个arg,导致if失败,因为表达式的计算结果为false:

php > $foo = array('t' => true, 'f' => false);
php > if ($foo['t'] ?? false) { echo 'true'; } else { echo 'false'; }
true
php > if ($foo['f'] ?? false) { echo 'true'; } else { echo 'false'; }
false
php > if ($foo['file_not_found'] ?? false) { echo 'true'; } else { echo 'false'; }
false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM