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 of 10 elements.
$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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With