Jump to content

Random Chance Function


Recommended Posts

Well, this is pretty simple to do, but hopefully it will help beginners who want to incorporate a chance into their script, but do not know how to go about it.



    This function creates a probability system. If the number is below the
	percentage provided, then it will trigger the code within the IF statement.
	If the number is above the percentage provided, then it will trigger the code
	within the ELSE statement.

	$num is an integer between 0 and 100.
	$perc is an integer that defines the probability of win vs. loss

	Currently if the number is less than or equal to the percentage, it will return true.
	If it is not, it will return false. This allows you to use it for many different
	situations. A demonstration is provided below the function.

    function chance($perc){

		$perc += 0;

	    $num = mt_rand(0, 100);

		    if($num <= $perc){
				return true;
			} else {
				return false;



	If returned true, print Successful!
	If returned false, print Failure!

	You can pretty much do anything with this as far as percentage goes. You could insert
	a value into the database on a win/loss, give the user a prize... It really doesn't 
	matter; It's completely up to you.


	    echo 'Successful!';
	} else {
		echo 'Failure!';

Link to comment
Share on other sites

Join the conversation

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

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

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