• 0

[PHP] Random True/False Function


Question

3 answers to this question

Recommended Posts

  • 0

I know you're already using rand, but I just thought I'd see if I could improve on what you had:

Personally I don't know of a quick function to do what your looking for.

<?php
function truefalse($trueperc, $falseperc) {
	if (($trueperc+$falseperc) !== 100) {
		echo 'Error invalid percentages';
	}
	$perc = rand(1,100);
	if ($perc < $trueperc) {
		return true;
	}
	elseif ($perc > $falseperc) {
		return false;
	}
}
?>

Btw, I'm not 100% on the logic I've used with more than and less than, but it appears to work with the test values I used. Ie. truefalse(1,99) returns false almost all the time.

  • 0

The idea works, yes, although I think the logic in AoM_Scott's code is flawed; see what truefalse(30, 70) does if the rand() generates 50.

I would use something like the following:

<?php
function rand_bool($chance = 50) {
   return (rand(1,100) <= $chance);
}
?>

...where the argument $chance is the wanted percentage (i.e. between 0 and 100) that the function returns true, with a default of 50%. It should work well enough for you.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.