使用循环创建数组

22 php arrays loops data-structures

我是非常新的PHP,我想知道是否有人可以帮助我使用for或while循环来创建一个长度为10个元素的数组

Owe*_*wen 25

$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 />";
Run Code Online (Sandbox Code Playgroud)

  • @I GIVE ...我发现这是不正确的,我根据高达750,000次迭代进行测试,发现$ array []在所有情况下都比$ array [$ i]更快(授予差异是一个问题千分之一秒 (2认同)

ale*_*lex 13

for循环的另一种方法是......

$array = array();

foreach(range(0, 9) as $i) {
    $array[] = 'new element';
}

print_r($array); // to see the contents
Run Code Online (Sandbox Code Playgroud)

我使用这种方法,我发现它更容易看一眼,看看它做了什么.

正如斯特拉格指出的那样,它可能会或可能不会更容易向您朗读.他/她还指出创建了一个临时数组,因此比正常的循环要贵一些.这个开销很小,所以我不介意这样做.你实施的是由你自己决定的.


Joh*_*n T 6

对于初学者来说可能更容易理解......

<?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++;
}

?>
Run Code Online (Sandbox Code Playgroud)