如何在 PHP 中创建一个预定义大小的空数组?
我正在 for 循环中创建一个新数组.
I am creating a new array in a for loop.
for $i < $number_of_items
$data[$i] = $some_data;
PHP 一直抱怨偏移量,因为每次迭代我都会为数组添加一个新索引,这有点愚蠢.
PHP keeps complaining about the offset since for each iteration I add a new index for the array, which is kind of stupid.
Notice: Undefined offset: 1 in include() (line 23 of /...
Notice: Undefined offset: 1 in include() (line 23 of /..
Notice: Undefined offset: 1 in include() (line 23 of /..
有什么办法可以预先定义数组中的项数,这样PHP就不会显示这个通知了吗?
Is there some way to predefine the number items in the array so that PHP will not show this notice?
换句话说,我可以用类似的方式预先定义数组的大小吗?
In other words, can I predefine the size of the array in a similar way to this?
$myarray = array($size_of_the_earray);
如果不提供数组元素的值,就无法创建预定义大小的数组.
There is no way to create an array of a predefined size without also supplying values for the elements of that array.
初始化数组的最佳方法是 array_fill代码>
.远远优于各种循环和插入解决方案.
The best way to initialize an array like that is array_fill
. By far preferable over the various loop-and-insert solutions.
$my_array = array_fill(0, $size_of_the_array, $some_data);
$my_array
中的每个位置都将包含 $some_data
.
Every position in the $my_array
will contain $some_data
.
array_fill
中的第一个零仅表示需要用值填充数组的索引.
The first zero in array_fill
just indicates the index from where the array needs to be filled with the value.