开发者

PHP Generate Array() from loop? [duplicate]

This question already has answers her开发者_如何学运维e: Create an array with a specified number of elements (5 answers) Closed 7 months ago.

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'));


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');
}


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'));


Your example looks fine to me, although you would most probably replace your array_push function call with:

$myarray[] = array('item' => '1 items');

Which "is" a shorthand syntax for array_push.

Update: For an associative array you just do:

$myarray["item"] = "1 items";

Although with your example you'll just overwrite the value on each iteration.


for($i=1; $i < 10; $i++) {
    $option[$i] = $i;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜