3

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, than use it later in my script.

1
  • Doesn't $my_var .= $i.'-' in the loop code work? Commented Oct 8, 2010 at 2:07

2 Answers 2

13

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(' ')), ' - ');
Sign up to request clarification or add additional context in comments.

4 Comments

@med Welcome to programming :)
I have 4 years of php development and always wandered about the .= and it came the time that I finally understood it. so it is used to append! thanks a lot!
+1 Are your alternative solutions examples of functional programming?
@medk: You said: "Thanks a lot! That's exactly what I need." A good follow-up to that sentence would be a click on the "Accepted" check.
0
$my_var = '';
for( $i = 1; $i <= 10; $i++ ) {

    $my_var .= $i' - ';

}
echo $my_var;

Hope it will work

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.