Jump to content

Is there anything like a random function?


iStriide

Recommended Posts

I'm wanting to know if there is a random function in PHP. I am not sure if there is one, but I could I do something where I can make something a have lets say a 25% chance of happening.

 

Example: Can I do anything like this?

25% chance of echoing "Whats Up" or 75% chance of echoing "I hate lag".

 

If there is anything like this any PHP I would appreciate if you guys would tell me how to use it.

Link to comment
Share on other sites

<?php
$variable = array("whats up","whats up","I hate lag","I hate lag","I hate lag");
$p1 = 0;
$p2 = 0;
for($i=0;$i<=100;$i++){


   shuffle($variable);
   if($variable[0] == "whats up"){ $p1++; } else { $p2++; }
   
   
}
print $p1 . '<br>';
print $p2;
  ?>  

 

 

34 - Whats up
67 - I hate Lag

25- Whats up
76- I hate Lag

37- Whats up
64 - I hate Lag

Link to comment
Share on other sites

$arr = array('whats up', 'I hate lag');
$rand = rand(1,25); // 25% chance max
$remainder = 100 - $rand;
echo $arr[0].' : '.$rand.'%<br />';
echo $arr[1].' : '.$remainder.'%<br />';

 

I would just to point out that this is not valid. Because Whats up and I Hate lag each half a 50/50 chance of happening in reality, while your only producing percentages not based on the array. OP's question wasn't very clear, because you would need to actually check how many times whats up and i hate lag occur based on the array elements.

 

Just a heads up.

 

I like your method though

Link to comment
Share on other sites

phpSensei

Small correction

In your method the total is 101, but if you change the “for loop” counting up to 99 then the total will be 100.

for($i=0;$i<=99;$i++){   

shuffle($variable);
if($variable[0] == "whats up"){ $p1++; } else { $p2++; } 
}

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.