Mustafa Temel
Mustafa Temel

Reputation: 65

I need to use variable, loop outside?

I have a simple loop

for($i=0;$i<10;$i++)
{
    $sample =  "";
    $sample    .= $i.", ";
}
echo $sample;

this outputs:

9,

How can I get this output instead?

1, 2, 3, 4, 5, 6, 7, 8, 9,

Upvotes: 2

Views: 33

Answers (1)

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41810

$sample = ""; initializes the variable to an empty string. Move that before your loop.

With that statement inside the loop, you're re-initializing $sample on each iteration. That's why you only see the last value.

$sample =  "";                 // here
for($i=0;$i<10;$i++)
{
                               // not here
    $sample    .= $i.", ";
}
echo $sample;

Upvotes: 5

Related Questions