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 10 elements in length
$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_push($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.
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++;
}
?>
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');
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.