php 使用循环创建数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/282916/
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
Using loops to create arrays
提问by Owen
I am extremely new at php and I was wondering if someone could help me use either a for or while loop to create an array 10 elements in length
我对 php 非常陌生,我想知道是否有人可以帮助我使用 for 或 while 循环来创建长度为 10 个元素的数组
回答by Owen
$array = array();
$array2 = array();
// for example
for ($i = 0; $i < 10; ++$i) {
$array[] = 'new element';
}
// while example
while (count($array2) < 10 ) {
$array2[] = 'new element';
}
print "For: ".count($array)."<br />";
print "While: ".count($array2)."<br />";
回答by alex
A different approach to the forloop would be...
for循环的另一种方法是......
$array = array();
foreach(range(0, 9) as $i) {
$array[] = 'new element';
}
print_r($array); // to see the contents
I use this method, I find it's easier to glance over to see what it does.
我使用这种方法,我发现浏览它更容易看到它的作用。
As stragerpointed out, it may or may not be easier to read to you. He/she also points out that a temporary array is created, and thus is slightly more expensive than a normal for loop. This overhead is minimal, so I don't mind doing it this way. What you implement is up to you.
正如strager指出的那样,它可能更容易阅读,也可能不会。他/她还指出创建了一个临时数组,因此比普通的 for 循环稍贵。这种开销很小,所以我不介意这样做。你实施什么取决于你。
回答by John T
a bit easier to comprehend for a beginner maybe...
对于初学者来说可能更容易理解......
<?php
// for loop
for ($i = 0; $i < 10; $i++) {
$myArray[$i] = "This is element ".$i." in the array";
echo $myArray[$i];
}
//while loop
$x = 0;
while ($x < 10) {
$someArray[$x] = "This is element ".$x." in the array";
echo $someArray[$x];
$x++;
}
?>
回答by nickf
I'm not sure exactly what your purpose is here. PHP's arrays are dynamic, meaning that you can keep adding elements to them after they're created - that is, you don't need to define the length of the array at the start. I'll assume you want want to put 10 arbitrary things in an array.
我不确定你在这里的目的到底是什么。PHP 的数组是动态的,这意味着您可以在创建元素后继续向它们添加元素——也就是说,您不需要在开始时定义数组的长度。我假设你想把 10 个任意的东西放在一个数组中。
for loop:
for循环:
$arr = array();
for ($i = 0; $i < 10; ++$i) {
$arr[] = "Element $i";
}
while loop:
while循环:
$arr = array();
$i = 10;
while (--$i) {
$arr[] = "Element $i";
}
by defining it:
通过定义它:
$arr = array("Element 1", "Element 2", "Element 3" ...);
Or if you just wanted a range of letters or numbers:
或者,如果您只想要一系列字母或数字:
$arr = range(0, 9);
$arr = range('a', 'j');
回答by too much php
The simplest way is to use array_fill():
最简单的方法是使用array_fill():
$array = array_fill(0, 10, 'Hello World');
But you should know that PHP arrays can be resized whenever you want anyway, I've never needed to create an array of a certain size.
但是您应该知道 PHP 数组可以随时调整大小,我从来不需要创建特定大小的数组。

