phparraysarray-key-exists

Check if array inside array exists in php


There is only ever one product returned at one time. When the product has an ingredient, my code works as intended. When it does not, I am getting:

Undefined offset: 0

Which references the line of code: if ($response_decoded['products'][0]['ingredients'] != null){

I understand this is because there is no ingredient, but there will be times when this is the case, it is unavoidable.

So, at this point:

$request->setMethod(HTTP_Request2::METHOD_GET);

$request->setBody("{body}");

try
{
    $response = $request->send();
    $result = $response->getBody();

    $response_decoded = json_decode($result,true);

    print_r($response_decoded);

...I am getting back:

Array ( [products] => Array ( [0] => Array ( [gtin] => 05052909299653 [tpnb] => 065738756 [tpnc] => 272043262 [description] => Tesco Lemon And Lime Zero 2L [brand] => TESCO [qtyContents] => Array ( [quantity] => 2000 [totalQuantity] => 2000 [quantityUom] => ml [netContents] => 2L e ) [productCharacteristics] => Array ( [isFood] => [isDrink] => 1 [healthScore] => 70 [isHazardous] => [storageType] => Ambient [isNonLiquidAnalgesic] => [containsLoperamide] => ) [ingredients] => Array ( [0] => Carbonated Water [1] => Citric Acid [2] => 

And so on...

I then do:

// check for ingredient array
if ($response_decoded['products'][0]['ingredients'] != null){

// can now target ingredient array
$ingredients = $response_decoded['products'][0]['ingredients'];

So rather than just != null I believe I need to check before hand if 'ingredients' even exists. I though I could use array_key_exists to do this.

if (array_key_exists('products', $response_decoded)) {
    echo "Product is there";

}
else{
    echo "Product is not there";

}

Now that works, it tells me if product exists... But how to check if ingredient for product exists?


Solution

  • If you're using PHP 7+, you don't need to check every dimension of the array -- you can use the null coalesce operator ?? on the final element:

    if ($response_decoded['products'][0]['ingredients'] ?? null !== null) {
        // ingredients exist
    }
    

    If the value exists and is not null, you'll fall into the condition. If any part of the array doesn't exist, it will fail, but won't complain with warnings about undefined indexes.