如何在 PHP 中创建一个预定义大小的空数组? [英] How to create an empty array in PHP with predefined size?

查看:124
本文介绍了如何在 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.

这篇关于如何在 PHP 中创建一个预定义大小的空数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆