Using loops to create arrays

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


$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 />";

A different approach to the for loop would be...

$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 strager pointed 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.


更容易理解一个初学者也许...

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

?>
链接地址: http://www.djcxy.com/p/59406.html

上一篇: 将()一个值推入多个数组

下一篇: 使用循环来创建数组