1

I'm trying to get a custom function in php to return a random number between 1 and 20 that does not repeat i.e. produce the same number more than once, since I need to subsequently use this number to navigate to one of twenty web pages, and I don't want the same web page displayed.

Here is my code in three steps:

<form action="rand.php">
        <p>Click this button to display a random number that does not repeat...</p>
        <p><input type="submit" value="Generate"></p>
    </form>

Here is rand.php:

require_once('functions.php');

$page = generateNumber();
echo $page;

Here is functions.php:

<?php

$check = array();

function generateNumber() {

    global $check;

    $page_no = mt_rand(1,20);
    $check[] = $page_no;

    if (count($check) != 1) {

        foreach ($check as $val) {
            if ($val == $page_no) {
                $page_no = mt_rand(1,10);
                continue;
            }
        }
        return $page_no;
    }
    else {
        return $page_no;
    }
}

?>

My code seem to be functioning, however, it is repeating numbers so I am obviously doing something wrong. The reason I initially check the count is so that is returns the first number regardless, since it would be a single fresh number.

In order to see the number change I have been refreshing the rand.php page in my browser.

user1574598
  • 3,771
  • 7
  • 44
  • 67
  • `$check[]` is not being populated with the current page number – cmorrissey Aug 25 '15 at 20:51
  • shuffle a range(0,20), loop through it –  Aug 25 '15 at 20:52
  • 2
    possible duplicate of [Generating UNIQUE Random Numbers within a range - PHP](http://stackoverflow.com/questions/5612656/generating-unique-random-numbers-within-a-range-php) – l'L'l Aug 25 '15 at 20:59
  • And you'll probably need to store the array in the session. Also, what happens when you've used all 20 numbers? – AbraCadaver Aug 25 '15 at 21:02
  • I will hope to catch it before it runs out of numbers by using the `count` function on a particular session variable that monitors how many questions people have answered for each web page, since this is for an online survey that is already up and running. Each time a person submits I use the `header` function to redirect to the next web page. Rather than page01 going to page02 and page03, etc. I want it to randomly pick a number that I can concatenate with a url string within the `header` function. E.g. `'www.website.com/page0' . $num . '.co.uk' – user1574598 Aug 27 '15 at 21:17

2 Answers2

7

I would keep it simple.

// List numbers 1 to 20
$pages = range(1,20);
// Shuffle numbers
shuffle($pages);
// Get a page
$page = array_shift($pages);
Dave
  • 3,658
  • 1
  • 16
  • 9
  • If this code is wrapped within a function lets say called `getPageNumber()`, will `shuffle` shuffle the numbers differently each time its called? Also, how can I make sure that your `pages` variable does not get re-initialised when a script re-runs i.e. when multiple form tags reference the same `.php` file, and therefore giving me a number I have already had? – user1574598 Sep 01 '15 at 20:01
0

In order to go through all the 20 numbers on each page visit, without repeating, you will need to set a session variable.

<?php
session_start();
if (!isset($_SESSION['numbers'])) {
    $_SESSION['numbers']="*"; //---create the session variable
}

function get_number() {
    $i = 0;
    do { 
        $num=rand(1,20); //---generate a random number
        if (!strstr($_SESSION['numbers'],"*".$num."*")) { //---check if the number has already been used
            $_SESSION['numbers']=$_SESSION['numbers'] . $i . "*"; //---add the number to the session variable to avoid repeating
            if (substr_count($_SESSION['numbers'],"*")>=21) { //---resets the session variable when all 20 number have been used
                $_SESSION['numbers']="*";
            }
            $i=$num; //---ends the while loop to return the value
         }  
    } while ($i==0);
    return $i;
}
?>
  • Dave your solution does not return a unique number between 1 and 20 envery time you run the scrit – Miguel Fernandes Aug 25 '15 at 22:37
  • Thanks. I like the simplicity of Dave's code, but if it does not return a unique number I will need to study and experiment with your code, since you are using functions I've not used before, and your technique with the `do while`. Why are you using an `*` frequently throughout the code? – user1574598 Aug 27 '15 at 21:03