Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.