简体   繁体   中英

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?

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.

You can use array_key_exists

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

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
}

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, ?? :

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

if price_change isn't set, ?? will return the second arg instead, causing the if to fail, since the expression would evaluate to 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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