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.
-
Ahh, the good old days ... if this question had been asked like this today, the user would be banned -user2835653– user28356532020-09-27 18:00:28 +00:00Commented Sep 27, 2020 at 18:00
-
@user2835653 I hope the user would be asked, "What have you tried so far?" instead of banned right away. At least that's how I would have approached it.crazymatt– crazymatt2020-10-28 19:28:12 +00:00Commented Oct 28, 2020 at 19:28
5 Answers
$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 />";
3 Comments
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.
2 Comments
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++;
}
?>
Comments
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.
for loop:
$arr = array();
for ($i = 0; $i < 10; ++$i) {
$arr[] = "Element $i";
}
while loop:
$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');
Comments
The simplest way is to use 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.