开发者

Storing a PHP loop as a string in a variable

I have a problem storing a PHP loop in a variable.

The loop is like this:

for( $i = 1; $i <= 10; $i++ ) {

    echo $i . ' - ';

}

for this it's OK for an echo or print as it will produce:

1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 -

now I want to store the whole loop in a variable like $my_var which means:

echo $my_var;

which will produce:

1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 -

the whole idea is that I want to make the loop, store it as a string in a variable $my_var开发者_Go百科, than use it later in my script.


Simply append the new string to the old one.

$str = '';

for( $i = 1; $i <= 10; $i++ ) {
    $str .= $i . ' - ';    
}

echo $str;

Alternatively, you could do...

$str = implode(range(1, 10), ' - ') . ' - ';

...or even...

$str = implode(array_merge(range(1, 10), array(' ')), ' - ');


$my_var = '';
for( $i = 1; $i <= 10; $i++ ) {

    $my_var .= $i' - ';

}
echo $my_var;

Hope it will work

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜