I saw this in my codebase today:
if (isset($purchase_data['buyer_tracking_address_id']) && $purchase_data['buyer_tracking_address_id']) {
// do something
}
Why would checking for both conditions be necessary? Isn't using just the first clause enough?
Isn't using just the first clause enough?
Edit I see the context of your question changed while I typed this answer. I think aynber's comment answers your question.
isset
is really only there to check for the existence of the array key buyer_tracking_address_id before the the next operation tries to access it. If it doesn't exist, isset will return false and will prevent the next condition from running.
Without isset
, if you tried to access the array key buyer_tracking_address_id and it didn't exist, PHP would throw a warning.
Warning: Undefined array key "buyer_tracking_address_id"
The following code will throw a notice in PHP 7, and a warning in PHP 8.
<?php
$purchase_data = [
'buyer_tracking_address_id' => '12345'
];
if ($purchase_data['doesnt_exist']) {
// do something
}
It is also worthwhile reading and understanding the ternary operator and the null coalescing operator as they are often used to access unknown array keys.