开发者

which is the right way of declaring an array to be used within the loop

Which would be the right way of decla开发者_StackOverflow社区ring an array inside a loop with regard to below example.

method 1:

$string = array();
for($i=0;$i<5;$i++)
{
  $string[] = $i;
}

method 2:

$string = array();
for($i=0;$i<5;$i++)
{
  $string = $i;
}

method 3:

for($i=0;$i<5;$i++)
{
  $string[] = $i;
}


option a would be the best:

$string = array();
for($i=0;$i<5;$i++)
{
  $string[] = $i;
}

this is because just in case u want to use $string later and you did not do anything in the loop, it still exists and you wont hit an error


1 and 3 will work, while 2 will overwrite the value of string every time.

1 is clearer but, if that's all there is in the loop, quite unnecessarily verbose.

Also, that variable name made me wonder: you don't plan to make a string out of that array, do you? In case, there's a better way.


I see you needed a string. In that case, what you should do is

 $string = '';
 for($i=0;$i<5;$i++) {
    $string .= $i;
 }

.= is a concatenation operator; appends right-side argument to left-side argument.


The first one is the best method .

second one just override the value and last value will be stored

and the third one is not declaring array that cause the php performance to be low. in this case php first create the array and then assign the value which is not a optimized way and take more time to executed php and at the last it take much time to execute your php script.

so first one is the best

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜