Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array with a specified number of elements

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.


2 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 />";
like image 57
Owen Avatar answered Sep 12 '25 09:09

Owen


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.

like image 37
alex Avatar answered Sep 12 '25 08:09

alex