<?php
function test_loop($string_name,$x)
{
$x = $x + 1;
if($x < 10)
{
$string_name = $string_name . $x . "##";
test_loop($string_name,$x);
}
return $string_name;
}
$bababa = test_loop(0,1);
echo $bababa;
//output is 02##
?>
How to make variable $bababa store value 02##3##4##5##6##7##8##9## ?
hi @2aek1987 and a warm welcome you the forum.
Try adding the following and see what is happening:
$x = $x + 1;
echo $x;
echo ' ==> ' .$string_name .'<br>'; // line feed
I will give you a hint: Your problem is here.
Solution if you can’t see it: You’re not catching the return from your inner function call.
Also that is a rather unnecessary use of recursion when a while loop would do just as well. But then, perhaps that’s the point of the exercise… Teaching you about variable scope.
i need to loop through higher and higher level uplines if found bigger and bigger package of upline’s purchase, so for loops is not enough for this. Need Recursive loop.
Solution is
function test_loop($string_name,$x)
{
$x = $x + 1;
if($x < 10)
{
$string_name = test_loop($string_name . $x . "##", $x);
}
return $string_name;
}
$bababa = test_loop(0,1);
<?php
$bababa = "0"
for($i = 2; $i < 10; $i++) {
$bababa .= $i."##";
}
echo $bababa;
?>
or if you’re feeling saucy:
<?php
echo "0".implode("##",range(2,9))."##";
?>
but yeah, sure. Recursion definitely needed. 