Search code examples
phpshopwareshopware6

Shopware 6 plugin: How to Resolve 'Undefined Array Key' Warning?


I'm working on a Shopware 6 plugin and encountering a warning related to accessing an array key that doesn't exist. Here's the relevant code snippet:

$customFields = $order->getCustomFields();
$optin = null;
if (array_key_exists('swag_product_reviews_optin', $customFields)) {
    $optin = $customFields['swag_product_reviews_optin'];
}
$text .= '  » Optin: ' . $optin;

As you can see, I'm checking if the 'swag_product_reviews_optin' key exists in the $customFields array before attempting to access it. However, I'm still getting the following warning:

Warning: Undefined array key "swag_product_reviews_optin"

Here's the full stack trace:

#0 /home/wokljnlu/sw66demo.wo-kaufen.de/vendor/symfony/http-kernel/HttpKernel.php(178): Swag\ProductReviews\Administration\Controller\SwagProductReviewsTestMailController->orderWhyNot()
#1 /home/wokljnlu/sw66demo.wo-kaufen.de/vendor/symfony/http-kernel/HttpKernel.php(76): Symfony\Component\HttpKernel\HttpKernel->handleRaw()
...

I'm not sure what could be causing this warning, as the code seems to be correctly checking for the key's existence before accessing it. My question is: What could be causing this "Undefined array key" warning in Shopware 6, even though I'm checking for the key's existence before accessing it? Is there something I'm missing or a better way to handle this scenario?

This code is executed in a controller action when an admin user triggers a specific route.


Solution

  • array_key_exists() raises a warning because $customFields can be null.

    You have a choice between isset() and array_key_exists(), it all depends on your specific use case and the requirements of your code. Here are some guidelines to help you decide when to use each function:

    Use isset() when you want to check if a variable or an array key is set and not null.

    Use array_key_exists() when you specifically want to check if a given key exists in an associative array, regardless of its value.

    If you prefer to use isset(), your code can be written as follows:

    $customFields = $order->getCustomFields();
    $customFieldKey = 'swag_product_reviews_optin';
    $optin = null;
    
    if (isset($customFields[$customFieldKey])) {
        $optin = $customFields[$customFieldKey];
    }
    
    $text .= '  » Optin: ' . $optin;
    

    If you want to use array_key_exists(), your code will look like this:

    $customFields = $order->getCustomFields();
    $customFieldKey = 'swag_product_reviews_optin';
    $optin = null;
    
    if (!empty($customFields) && array_key_exists($customFieldKey, $customFields)) {
        $optin = $customFields[$customFieldKey];
    }
    
    $text .= '  » Optin: ' . $optin;