0

I have a PHP script with a while loop and I need to return the result as a single variable !

Code schema :

$count = "0";
while($count < "4")
{
 echo $count;
 $count = $count + "1";
}

It will return : 0123, What I want to have a variable with the value : 0123

I also tried :

$count = "0";
while($count < "4")
{
 $result .= $count;
 $count = $count + "1";
}
echo $result;

But it will show the result like : 0010120123

I know I can use array to get all results outside the loop, but I want to have all results as a single variable but not in an array !

Update : I found the problem :S stupid mistake ! I used :

echo $result

Inside my loop :S So

$result .= $count;

Work fine :)

6
  • Yes $rresult also print 0123 Commented Feb 2, 2017 at 12:03
  • You means 01234..... etc ? Commented Feb 2, 2017 at 12:09
  • no only 0123 as per Lynxis Commented Feb 2, 2017 at 12:10
  • So its printing right ? whats the problem Commented Feb 2, 2017 at 12:11
  • @BharatDangar ur right, it work correctly :) Commented Feb 2, 2017 at 12:18

3 Answers 3

1
$count = "0";
$var = "";
while($count < "4")
{
 $var .= $count;
 $count++;
}
echo $var;
Sign up to request clarification or add additional context in comments.

Comments

0

Here is a function that can do it to you

Pass 4 in the parametrs to match your example

function abc($limit){  
    $count = "";
    for($i=0; $i<$limit; $i++)
    { 
         $count .= $i;
    }
    return $count;
}

echo abc(4); // outputs 01234

Comments

0

Try this, it should do it:

<?php

$count = "0";
$var = "";
while($count < "4")
{
 $var .= $count;
 $count++;
}

echo $var;

?>

Comments

Your Answer

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