drumichael611 drumichael611 - 3 months ago 6
PHP Question

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.

Answer

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
}