Click here to Skip to main content
15,890,399 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to return string that extended by recursive loop in a php function?


What I have tried:

<?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## ?
Posted
Updated 28-Apr-20 21:37pm

1 solution

You need to use the return value inside the function, as well as outside it ...
PHP
test_loop($string_name,$x);
Does the work, but throws away the answer ...
Try this:
PHP
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);
 
Share this answer
 
Comments
Zac Ang 29-Apr-20 4:27am    
Perfect. Thank you very much.
OriginalGriff 29-Apr-20 4:33am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900