DEV Community

Kelly Okere
Kelly Okere

Posted on

How to generate random number in PHP

Ever wondered how to generate random numbers in PHP using a simple function while excluding some numbers you don't want, just like a friend of mine that requested for this code?

Here's how to do it:

<?php
function generateRandomNumber($min, $max, $excludedNumbersArr) {
    do {
        $number = rand($min, $max);
    } while (in_array($number, $excludedNumbersArr));

    return $number;
}

// Use it this way
echo generateRandomNumber(50,250,[123,145]); //This PHP function generates a number between 50 and 250, excluding 123 and 145.
?>
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. Set the Range: The function defines the minimum ($min) and maximum ($max) values for the random number.
  2. Excluded Numbers: An array $excludedNumbersArr contains the numbers you want to exclude.
  3. Generate Random Number: A do-while loop generates a random number using rand($min, $max). It continues to generate a new number until the number is not in the $excludedNumbersArr array.
  4. in_array(): This is a PHP function that checks if a value exists in an array. It takes two parameters:

    Value: The value you want to search for.
    Array: The array in which you want to search for the value.

  5. Return the Number: Once a valid number is generated, it is returned.

This function ensures that the generated number is within the specified range and does not include the excluded values.

Thanks for reading this article.

I write codes on demand. Let me know the code you need, and I will help you write them in your programming language.

PS:
I love coffee, and writing these articles takes a lot of it! If you enjoy my content and would like to support my work, you can buy me a cup of coffee. Your support helps me to keep writing great content and stay energized. Thank you for your kindness!
Buy Me A Coffee.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (2)

Collapse
 
drazenbebic profile image
Drazen Bebic

That's a nifty function, but please be aware that these random strings are not cryptographically safe and should therefore not be used for encryption.

Collapse
 
kellyblaire profile image
Kelly Okere • Edited

Thanks for your feedback, Drazen.

It's important to note that this function is not meant for encryption purposes. It's just a basic function for generating random codes within a certain range of numbers while ignoring any number within a given array.

There are more cryptographically safe approaches to generate random numbers for encryption purposes, and this is not one of them.

For encryption purposes, one can use the functions introduced in PHP 7 and above, like random_int() or random_bytes() (with some tweaks), or even the legendary openssl_random_pseudo_bytes() (for older versions of PHP).

Maybe I'll update the post for clarity.

Thanks again.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay