Jump to content

[SOLVED] Why this is not working?


gtal3x

Recommended Posts

It should return any random number from 0 to 10 exept the numbers that are in $used... However the script sometimes returns the numbers thats its not supost to return... any idea why?

<?php
$used = array("0","1","2","3","4","5","6");
$number = rand(0,10);

for ($i=0;$i<=4;$i++){ 
while ($number == $used[$i]) {
$number = rand(0,10);	
}
}
echo $number;
?>

Link to comment
Share on other sites

You need to use the in_array() function to determine if a particular value is in an array:

 

<?php
$used = array("0","1","2","3","4","5","6");
$number = rand(0,10);
while(in_array($number,$used)){
$number = rand(0,10);
}
echo 'Number: '.$number;
?>

 

Of course, the above code would enter into an infinite loop should all the possible numbers gererated by the rand() function be in the $used array.

Link to comment
Share on other sites

check out this post

 

http://www.phpfreaks.com/forums/index.php/topic,167350.0.html

 

a function I wrote following is the code

 

<?php

function urand($intMin,$intMax,$strExclude)
{
$arrExclude = explode(",",$strExclude);

while ($intTempRand = rand($intMin,$intMax))
{
	if (!in_array($intTempRand,$arrExclude))
	{
		return  $intTempRand;
	}
}
}

$excluding = '1,6,8,9';
$rand = urand(1,10,"$excluding");
echo $rand;
?>

Link to comment
Share on other sites

Perfect opertunity for recursion.

 

<?php

 function getrand($used) {
   $number = rand(0,10);
   if (in_array($number,$used)) {
     $number = getrand($used);
   }
   return $number;
 }

 echo getrand(range(0,6));

?>

Link to comment
Share on other sites

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.