w3resource

PHP Array Exercises : Generate unique random numbers within a range


15. Generate Unique Random Numbers within a Range

Write a PHP script to generate unique random numbers within a range.

Sample Range : (11, 20)

Sample Solution:

PHP Code:

<?php
// Generate an array containing numbers from 11 to 20 using 'range'
$n = range(11, 20);

// Shuffle the elements of the array using 'shuffle'
shuffle($n);

// Use a 'for' loop to iterate 10 times
for ($x = 0; $x < 10; $x++)
{
    // Echo the current element of the shuffled array followed by a space
    echo $n[$x] . ' ';
}

// Echo a newline character for better formatting
echo "\n";

?>

Output:

17 19 13 15 20 14 12 18 11 16    

Flowchart:

Flowchart: Generate unique random numbers within a range

For more Practice: Solve these Related Problems:

  • Write a PHP script to generate a shuffled list of unique random numbers between a given range and display them in sorted order.
  • Write a PHP function to create an array of unique random integers within a specified range using a loop and validation.
  • Write a PHP program to generate unique random numbers between 11 and 20 and check for duplicates before final output.
  • Write a PHP script to simulate a lottery drawing by generating and printing a set of unique random numbers from a given range.

Go to:


PREV : Get Shortest and Longest String Length from Array.
NEXT : Get the Largest Key in an Array.

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.