[ACCEPTED]-PHP Generate Array() from loop?-while-loop
Your code has a couple of things which can 11 be improved:
Magic Numbers
It's a bad practice to assign 10 magic numbers like 4 and 1, use constants 9 instead. For this example it's of course 8 overkill but still important to know and 7 use.
Lack of braces
Always use the curly braces, it makes 6 the code more readable.
Wrong use of while loop
This is not a case 5 for a while loop, if you want to loop a 4 certain number of times, always use a for 3 loop!
Unnessesary use of array_push
You don't need array push to add elements 2 to an array, you can and should probably 1 use the shorthand function.
Result:
define('START', 1);
define('END', 4);
$myArray = array();
for ($i = START; $i < END; $i++)
{
$myArray[] = array('item' => '1 items');
}
I'd personally do the following looking 2 at your code:
$myarray = array();
for($i=0;$i<4;$i++){
$myarray[] = array('item' => '1 items');
}
According to this, array_push is 1 a little less efficient than $myarray[]
If you really need to only put a certain 2 value n times into an array starting from 1 a certain index, you could just use array_fill
:
$myarray = array_fill($i, $c, array('item' => '1 items'));
Your example looks fine to me, although 5 you would most probably replace your array_push
function 4 call with:
$myarray[] = array('item' => '1 items');
Which "is" a shorthand syntax 3 for array_push.
Update: For an associative array 2 you just do:
$myarray["item"] = "1 items";
Although with your example you'll 1 just overwrite the value on each iteration.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.