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.
Aucun commentaire:
Enregistrer un commentaire