php 在php中如何设置数组的大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5560103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In php how do I set the size of an array?
提问by dave
I just want to set the size of an array in php, without having to fill it up with any values. How do I do that?
我只想在 php 中设置数组的大小,而不必用任何值填充它。我怎么做?
回答by netcoder
Use SplFixedArrayfor a fixed-size array:
将SplFixedArray用于固定大小的数组:
$array = new SplFixedArray(3);
$array[0] = 1;
$array[1] = 2;
$array[2] = 3;
$array[3] = 4; // RuntimeException
回答by Mark Elliot
In PHP arrays are really ordered maps and thus have size equal to the number of elements they contain -- if you want to create an empty array of a particular size you're going to have to fill it with something.
在 PHP 中,数组实际上是有序的映射,因此其大小等于它们包含的元素数量——如果您想创建一个特定大小的空数组,您将不得不用一些东西填充它。
You could always fill it with null
values using array_fill
:
您始终可以使用以下null
值填充它array_fill
:
$empty_arr = array_fill(0, $size, NULL);
回答by Jacob
Arraysdon't have a set size, they are dynamic (not stored the same as other languages such as C).
数组没有固定大小,它们是动态的(与 C 等其他语言的存储方式不同)。
If you want to specify an array with a size for performance reasons, look at:
如果出于性能原因要指定具有大小的数组,请查看:
SplFixedArrayin the Standard PHP Library.
标准 PHP 库中的SplFixedArray。
回答by Mike Lewis
You have to add elements to the array to change the size. Whether it is with the value of null, or otherwise.. you must add some element to change the size.
您必须向数组添加元素才能更改大小。无论是带有null值还是其他..您必须添加一些元素来更改大小。