首页 > 解决方案 > PHP 7 Multidimensional Array Initialization

问题描述

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.

标签: phparraysmultidimensional-array

解决方案


如果您分配嵌套数组,它们确实会自动创建(没有通知错误),但是由于您说incrementing,听起来好像您在初始化之前访问该值。增加不存在的变量或键$var++会导致警告,因为它等于$var = $var + 1,并且在变量存在之前评估右侧。

这可以通过首先将密钥设置为零来避免。

在 PHP7 中,一个简单的方法是使用$var ??= 0. 如果它不包含非零值,它将初始化$var0,但不会覆盖现有的非零值。

例如,以下代码将初始化一个数组键,然后将其递增两次,而不会发出 e_notice 警告。

$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)
  }
}

推荐阅读