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'));
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.
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!!
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.
Your code has a couple of things which can be improved:
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.
Always use the curly braces, it makes the code more readable.
This is not a case for a while loop, if you want to loop a certain number of times, always use a for loop!
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');
}
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[]
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'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With