Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Generate Array() from loop?

I just wrote this up, is this the most efficient way to add arrays to a preexisting array.


$c=4;
$i=1;
$myarray = array();

while($i <= $c):
    array_push($myarray, array('key' => 'value'));
    $i++;
endwhile;

echo '<pre><code>';
var_dump($myarray);
echo '</code></pre>';

Update: How would you push the key & value, without creating a new array.
so this array_push($myarray,'key' => 'value');
not this array_push($myarray, array('key' => 'value'));

like image 995
kr1zmo Avatar asked Mar 19 '11 00:03

kr1zmo


People also ask

How do you make an array while loop?

All you have to do is initialize the index that points to last element of the array, decrement it during each iteration, and have a condition that index is greater than or equal to zero. In the following program, we initialize an array, and traverse the elements of array from end to start using while loop.

How can we store values from for loop into an array in PHP?

Declare the $items array outside the loop and use $items[] to add items to the array: $items = array(); foreach($group_membership as $username) { $items[] = $username; } print_r($items); Hope it helps!!

How do I traverse an array in PHP?

Traversing: We can traverse an indexed array using loops in PHP. We can loop through the indexed array in two ways. First by using for loop and secondly by using foreach.


3 Answers

Your code has a couple of things which can be improved:

Magic Numbers

It's a bad practice to assign magic numbers like 4 and 1, use constants instead. For this example it's of course overkill but still important to know and use.

Lack of braces

Always use the curly braces, it makes the code more readable.

Wrong use of while loop

This is not a case for a while loop, if you want to loop a certain number of times, always use a for loop!

Unnessesary use of array_push

You don't need array push to add elements to an array, you can and should probably use the shorthand function.

Result:

define('START', 1);
define('END', 4);

$myArray = array();


for ($i = START; $i < END; $i++)
{
    $myArray[] = array('item' => '1 items');
}
like image 195
markus Avatar answered Oct 16 '22 12:10

markus


I'd personally do the following looking at your code:

$myarray = array();
for($i=0;$i<4;$i++){
  $myarray[] = array('item' => '1 items');
}      

According to this, array_push is a little less efficient than $myarray[]

like image 28
Prisoner Avatar answered Oct 16 '22 10:10

Prisoner


If you really need to only put a certain value n times into an array starting from a certain index, you could just use array_fill:

$myarray = array_fill($i, $c, array('item' => '1 items'));
like image 43
NikiC Avatar answered Oct 16 '22 12:10

NikiC