Home > OS >  PHP 7 Multidimensional Array Initialization
PHP 7 Multidimensional Array Initialization

Time:10-21

I wrote these PHP scripts maybe 10 years ago, most likely on PHP 4, but maybe on 3. I worked on them a couple years ago and got them to work on PHP 5, but now my host has upgraded to PHP 7, and I am throwing undefined offset errors by the hundreds if not thousands. I was under the impression that if I try to load a value into an undefined array, that it would create the index, but apparently not. So my solution is to simply create the empty array to avoid this. I am just trying to determine if nested loops are the only solution. We are a preschool, and for my first script, my arrays are things like:

$childs_classroom[classroom][week][day_of_week]

classroom is 0-4, weeks 0-260, and dow 0-4

When I try to increment an array like this, it creates an undefined offset error every time (I believe). Is there a simpler way other than nested loops to create this array and fill it with nulls/zeroes so I don't get errors? I apologize if this is basic stuff, I've forgotten more about PHP than I remember atm.

CodePudding user response:

Nested arrays are indeed automatically created (with no notice error) if you assign them, but since you say incrementing, it sounds as though you are accessing the value prior to initialization. Incrementing a non-existent variable or key with $var will cause warnings, as it is equal to $var = $var 1, and the right-hand side is evaluated before the variable exists.

This can be avoided by setting the key to zero first.

In PHP7, an easy way to do this is to use $var ??= 0. This will initialize $var to 0 if it does not contain a non-zero value yet, but will not overwrite an existing non-zero value.

For example, the following code will initialize an array key, then increment it twice, without emitting e_notice warnings.

$non_existent_array['non_existent']['key'] ??= 0;
$non_existent_array['non_existent']['key']  ;

var_dump($non_existent_array);

$non_existent_array['non_existent']['key'] ??= 0;
$non_existent_array['non_existent']['key']  ;

var_dump($non_existent_array);



array(1) {
  ["non_existent"]=>
  array(1) {
    ["key"]=>
    int(1)
  }
}
array(1) {
  ["non_existent"]=>
  array(1) {
    ["key"]=>
    int(2)
  }
}

CodePudding user response:

You can bypass warnings with null coalescing operator (??) in PHP7. Example:

echo $childs_classroom[classroom][week][day_of_week] ?? "N/A"

will print the value if exists, or N/A

  • Related