如何用在循环中创建的变量填充循环中的数组(在php中)


how to fill an array in a loop with variables which are created in this loop (in php)?

我想在循环中生成或填充一个数组,其中包含变量(在php中)。但是这些变量是在这个循环中编写的。

举个例子:

$i = 1;
while(i<10){
    $a = array("$i","$i","$i");  
    i++;
}

第二个和第三个i变量应该在下一段中添加。最后,数组将包含从0到10的数字。我发现了一些带有$$变量的东西,但我不认为这是有用的用法。

有什么可能的方法?谢谢:)

我认为您陷入了困境,因为您不知道如何将元素添加到数组中,这是非常基本的事情。

只需在每次迭代中向数组中添加一个元素,如下所示:

$i = 0;
while($i < 10) { //If you want 0 - 10 including 10, just change '=' to '<='
    $a[] = $i;  
    $i++;  //Assuming, that the missing dollar signs are typos, since you already did it right once
}

在此处阅读有关阵列的更多信息:http://php.net/manual/en/language.types.array.php

另一种方法是只使用range():

$a=range(0,10);