Jump to content

[SOLVED] Recursive Function Problem


Panruru

Recommended Posts

I'm trying to create a simple function that will return a random number between 0 and a variable, and check a $_SESSION array to make sure it never returns the same number twice. Unfortunately, I kind of suck at programming and seem to be failing. =_=

 

The function:

 

function rndTerm($totalTerms)
{
$rndTerm = rand(0, $totalTerms);

//ensures that the number of values in $_SESSION["used"] never exceeds a certain point		
if ((count($_SESSION["used"]) <= $totalTerms))
{
      //theoretically, if $rndTerm is already in $_SESSION["used"] the function should loop back through itself until it finds a value that's not. Unfortunately, I seem to be doing something terribly wrong.
	if (isset($_SESSION["used"][$rndTerm])) 
	{
		$rndTerm = rndTerm($totalTerms);
	}
}
else
{
	$rndTerm = "null";
}
	return $rndTerm;
}

 

I'm probably blind, but could someone please help me out? I can't figure this out at all.

Link to comment
https://forums.phpfreaks.com/topic/155680-solved-recursive-function-problem/
Share on other sites

try changing

if (isset($_SESSION["used"][$rndTerm])) 

to this

if (in_array($rndTerm, $_SESSION["used"])) 

 

you may have mixed up your values and keys. say rndterm is 2, and you have done this function three times, you are checking if there is a value for the key of _SESSION['used'][2] and since this function has executed three times, there would be (Assuming you are using a numeric array)

 

Hope that helps

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.