PHP automatically creates sub-keys if they don't exist (and you can avoid the notice by checking isset
). If you wish, feel free to create a function that does it for you (minimizes the double-pasting of variables.
Code:
<?php
error_reporting(E_ALL);
function setDefault(&$variable, $default) {
if (!isset($variable)) {
$variable = $default;
}
}
$foo = array(
'foo' => 'oof'
);
setDefault($foo['sub']['arrays']['are']['pretty']['cool'], 0);
print_r($foo);
?>
Outputs:
Array
(
[foo] => oof
[sub] => Array
(
[arrays] => Array
(
[are] => Array
(
[pretty] => Array
(
[cool] => 0
)
)
)
)
)
3v4l shows that there's no notice in any PHP version from 4.3.0 to 5.5.6 compared to this that clearly spits out a notice.
If you don't want to use a function, feel free to just use the last if
condition in your code:
<?php
error_reporting(E_ALL);
$foo = array(
'foo' => 'oof'
);
if (!isset($foo['sub']['arrays']['are']['pretty']['cool'])) {
$foo['sub']['arrays']['are']['pretty']['cool'] = 0;
}
print_r($foo);
?>