Question

I am having a custom module for magento 2.4.2 but with php 7.4 I am having this issue:

Notice: Trying to access array offset on value of type null in /public_html/app/code/mymodule/Helper/Data.php on line 242

when trying to save a product in my admin.

My code in this line is:

if (!is_array($section['fields'])) continue;

And the whole //check is:

$sectionOrder = -1;
            foreach($sections as $key => $section) {
                $sectionOrder++;
                if (!is_array($section['fields'])) continue;
                if (isset($section['template_id']) && !in_array((int) $section['template_id'], $templateIds)) {
                    unset($sections[$key]);
                    $sectionOrder--;
                    continue;
                }
                $sections[$key]['order'] = $sectionOrder;
                foreach($section['fields'] as $key2 => $_field) {
                    if (!is_array($_field)) continue;
                    $sections[$key]['fields'][$key2]['section_order'] = $sectionOrder;
                }
            }

With php 7.3 it works but with 7.4 I have problem.

Any help please how I can write this? Thanks in advance!

Was it helpful?

Solution

It looks like the source of the error comes from $section not being an array sometimes, but it wouldn't hurt to also account for array keys on $section not being set when it is an array.

PHP's Null Coalescing Operator is useful here for accounting for the non-existing array key.

Example of changed line:

This covers the case when fields is not set or null. The ?? operator will return the left operand if it is set and is not null, otherwise it will return the right operand of false which is definitely not an array:

if (!is_array($section['fields'] ?? false)) continue;

This will cover the case where $section itself is null and not an array:

if (!is_array($section) || !is_array($section['fields'] ?? false)) continue;

Example Use of Null Coalescing Operator

<?php

$foo = [
    'bar' => 'Some Value'
];

// The key 'baz' does not exist
$baz = $foo['baz'] ?? 'nothing';

// The array offset error will be prevented.
// Output will be: 'nothing'
echo $baz;    

Example Directly From php.net

Referenced from: PHP 7.0 new features

<?php
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top