Doing Random Things in PHP

Read {count} times since 2020

Suppose you want to display something randomly in a news feed, or pick random elements from an array, or anything random in general. Programming Languages are used to define the way how something must be done. Hence in a technical way, it can’t do things randomly on it’s own. Otherwise it would be an AI (Artificial Intelligence). Doing random things is not done at compiling, but in execution. In case of PHP, this doesn’t matter as it’s an interpreter.


In situations like generating random salts for password and other security related things, you shouldn’t use this. There are really better functions to do those like random_int()openssl_random_pseudo_bytes()

The Problem

The Random Function is useful in these scenarios :

There isn’t a definite function in PHP to do something at random. How about we make one ?

The Solution aka random()

Meet the function random() which will return positive (In boolean terms, it’s called TRUE), and negative if it’s not the right time to do something.

 * $occurence - integer
 * $range - integer
function random($occurence = 3, $range = 100){
  return mt_rand(1, $range) % $occurence === 0;

By tweaking the $occurence parameter, you can increase/decrease the possibility ie returning TRUE. $range can be used to increase/decrease the scope of randomness. Example: By increasing both $occurence and $range, the possibility of getting a **TRUE **output decreases. It is inversely proportional. Note that :

$range > $occurence

Which means, tweaking $occurence has greater effect on the randomness than $range. Yeah, it’s confusing. You can decrease this confusion by reading the How It Works ?

How It Works

As you may know, there is already a function in PHP to get a random number ie rand(). We simply uses it to return TRUE/FALSE instead of numbers. So, how is it done ? By checking whether the random number is divisible by the integer in $occurence. The random number is made from :

1 – $range

^ I omitted zero as 0 can be divided by any number. As the random number is random (obviously!), it won’t be always divisible by $occurence. So, when it is divisible, you get a TRUE return value and when it’s not divisible you get a FALSE return value. This is why I earlier stated that :

Tweaking $occurence has greater effect on the randomness than $range.

Increasing $range would just increase the list from where the random number is picked. This means that the altering of the randomness will be small. But, if you change $occurence, the whole scenario changes and the randomness dramatically changes. Here’s a test case running random() in a loop for 100 iterations  :

$occurence Number of Outcomes That Were TRUE
1 100
2 38
3 35
4 18
5 21
6 9
7 14

As you can see the TRUE outcomes didn’t decrease proportionally ie it’s absolutely random.

Show Comments