我在for循环中创建一个新数组.
for $i < $number_of_items
$data[$i] = $some_data;
Run Code Online (Sandbox Code Playgroud)
PHP一直抱怨偏移,因为每次迭代我都会为数组添加一个新的索引,这有点愚蠢.
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 /..
Run Code Online (Sandbox Code Playgroud)
有没有办法预定义数组中的数字项,以便PHP不会显示此通知?
换句话说,我可以用与此类似的方式预定义数组的大小吗?
$myarray = array($size_of_the_earray);
Run Code Online (Sandbox Code Playgroud)
Jon*_*Jon 85
无法为该数组的元素提供值,也无法创建预定义大小的数组.
初始化这样的数组的最佳方法是array_fill.迄今为止优于各种环路和插入解决方案.
$my_array = array_fill(0, $size_of_the_array, $some_data);
Run Code Online (Sandbox Code Playgroud)
$my_array遗嘱中的每个位置都包含$some_data.
第一个零array_fill只表示数组需要用该值填充的索引.
Jea*_*erc 17
你不能在php中预定义数组的大小.实现目标的一个好方法是:
// Create a new array.
$array = array();
// Add an item while $i < yourWantedItemQuantity
for ($i = 0; $i < $number_of_items; $i++)
{
array_push($array, $some_data);
//or $array[] = $some_data; for single items.
}
Run Code Online (Sandbox Code Playgroud)
请注意,使用array_fill()填充数组会更快:
$array = array_fill(0,$number_of_items, $some_data);
Run Code Online (Sandbox Code Playgroud)
如果要验证是否已在索引处设置了值,则应使用以下命令:array_key_exists("key",$ array)或isset($ array ["key"])
请参见array_key_exists , isset 和 array_fill
Mad*_*aks 13
可能相关,如果要初始化并使用一系列值填充数组,请使用PHP(等待它......)范围函数:
$a = range(1, 5); // array(1,2,3,4,5)
$a = range(0, 10, 2); // array(0,2,4,6,8,10)
Run Code Online (Sandbox Code Playgroud)
PHP数组不需要使用大小声明.
PHP中的数组实际上是一个有序映射
您也不应该使用您所示示例之类的代码获得警告/通知.人们从数组中读取的常见通知是"Undefined offset".
对付这种情况的方法是检查与isset或array_key_exists,或使用功能,例如:
function isset_or($array, $key, $default = NULL) {
return isset($array[$key]) ? $array[$key] : $default;
}
Run Code Online (Sandbox Code Playgroud)
这样你就可以避免重复的代码了.
注意:isset如果数组中的元素为NULL,但性能增益超过,则返回false array_key_exists.
如果要出于性能原因指定大小的数组,请查看:
标准PHP库中的SplFixedArray.
小智 5
$array = new SplFixedArray(5);
echo $array->getSize()."\n";
Run Code Online (Sandbox Code Playgroud)
您可以使用 PHP 文档更多信息查看此链接 https://www.php.net/manual/en/splfixedarray.setsize.php