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
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.
<?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';
?>