Reputation: 151
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.
Upvotes: 0
Views: 79
Reputation: 360842
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
Upvotes: 0
Reputation: 54796
Use empty()
function. It will check both condtions
false
or 0
or empty string
Example:
if (!empty($audit['price_changed'])) {
// do something
}
Upvotes: 2
Reputation: 111
if (array_key_exists('price_changed', $audit)) {
.... do something ....
}
Upvotes: 2
Reputation: 3360
Rather than using a nested if you can simply do:
if(isset($audit['price_changed']) && $audit['price_changed']) {
// do something ...
}
Upvotes: 0