How to stop php recursive loop when return value?

function test_loop($x_values,$x, $y)
{
    $x = $x + 1;
    if($x < 4)
    {
    	//I want to add $x value into $x_values variable, eg : $x_values = $x_values . $x;
	    //but $x_values = $x_values . $x; is not working, so I force to use $x_values = test_loop($x_values . $x . "##", $x, $y);
        $x_values = test_loop($x_values . $x . "##", $x, $y);
    }
    
    //loop again if y is not = 3;
    $y = $y + 1;
    if($y < 3)
    {
    	echo "kkk" . $y . "<br/>";
		$x_values = test_loop($x_values . $x . "##", $x, $y); 
	}else{
		echo "---------------------<br/>";
	}

	return $x_values; 
}

function abc(){
	$bababa = test_loop(0,1,0);

	echo $bababa;
}

abc();

Output :

kkk1
kkk2
---------------------
kkk1
kkk2
---------------------
kkk1
kkk2
---------------------
kkk2
---------------------
02##3##4##5##3##4##2##3##4##3##

How to make the output become :

kkk1
kkk2
---------------------
02##3##

In what way does $x_values = $x_values . $x (or indeed the shorter $x_values .= $x) not work?

If the issue is that you’re only returning one value from the function, which means that anything you do to $x and $y inside the function are lost, don’t forget you can return an array or an object, which can contain multiple values.

It might be better if you could describe the actual problem you’re trying to solve, what needs to happen and why it needs to stop where you want it to. It’s difficult to offer solutions without knowing the problem.

1 Like

Don’t forget numerous PHP function parameters can also be returned by reference by prefixing an ampersand.

https://www.php.net/manual/en/language.references.pass.php

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.