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
https://forums.phpfreaks.com/topic/78430-solved-why-this-is-not-working/
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.

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;
?>

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.