Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 53 / 68

Generating Random Numbers

In this lesson you will learn to generate random values with rand and array_rand so you can build things like dice and raffles. This is for anyone searching for "PHP random number generation".

rand() and array_rand() give you a random number, or a randomly chosen value from an array. Use them for dice rolls and raffles. The result changes every time you run it.

The sample code rolls a die from 1 to 6 with rand(1, 6) and picks one of Rock, Scissors, and Paper with $choices[array_rand($choices)]. Notice that array_rand() returns the chosen index, not the chosen element.

A common stumbling block for beginners is exactly that: array_rand() returns a key rather than a value. You have to use the returned key to look the value up, as in $choices[array_rand($choices)], and that two-step flow is easy to miss.

There is also random_int(), a safer generator recommended wherever security matters. Shuffling in a game or sampling in a simulation are among the many practical uses.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)