Storing a PHP loop as a string in a variable -


i have problem storing php loop in variable.

the loop this:

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

for it's ok echo or print produce:

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

now want store whole loop in variable $my_var means:

echo $my_var; 

which produce:

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

the whole idea want make loop, store string in variable $my_var, use later in script.

simply append new string old one.

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

alternatively, do...

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

...or even...

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

Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -