• Skip to content
  • Skip to primary sidebar

MTZ - My Techno Zone

mytechnozone.com is a website where you can find Tutorials related to Blogging, Wordpress, Elementor, Woocommerce and many other web development related tips and tricks.

  • Home
  • Blogging
  • Website Development
  • Android
You are here: Home / Tutorials / Create a Random number generator program using PHP

Create a Random number generator program using PHP

Today we are going to create a simple Random number generator program with the help of PHP. Here’s a simple PHP program that generates a random number within a specified range of numbers:

<?php

// Function to generate a random number within a given range
function randomNumber($min, $max) {
  // Generate a random number between 0 and 1
  $rand = mt_rand() / mt_getrandmax();

  // Scale the random number to the desired range
  return $min + $rand * ($max - $min);
}

// Read the minimum and maximum values from the user
echo "Enter the minimum value: ";
$min = trim(fgets(STDIN));

echo "Enter the maximum value: ";
$max = trim(fgets(STDIN));

// Generate a random number within the given range
$rand = randomNumber($min, $max);

// Display the random number
echo "The random number is: $rand\n";

?>

This program defines a function randomNumber() that takes two arguments: the minimum and maximum values of the range within which to generate the random number. The function uses the mt_rand() and mt_getrandmax() functions to generate a random number between 0 and 1, and then scales this number to the desired range using the formula $min + $rand * ($max - $min).

The program then prompts the user to enter the minimum and maximum values of the range, reads the input, and calls the randomNumber() function to generate a random number within this range. Finally, it displays the random number to the user.

I hope this helps! Let me know if you have any questions.

Filed Under: Tutorials

Reader Interactions

Primary Sidebar

Categories

  • affiliate marketing
  • Blogging
  • Crypto
  • Elementor
  • Interview Questions
  • jQuery
  • Make money online
  • Programming languages
  • React Interview Questions
  • Tutorials
  • Webhosting
  • Website Development
  • whatsapp
  • woocommerce
  • Wordpress

Recents blog posts

  • Write a program to gererate fabonicci series using PHP
  • Create a Random number generator program using PHP
  • Write a Prime number checker program using PHP

Quick links

  • Disclaimer
  • About me
  • Privacy Policy

© 2023 · mytechnozone.com