Jump to content

[SOLVED] How to generate unique number


jagoan-neon

Recommended Posts

Hello Masters, I need a little help.

 

this is my code

 

<?
$array = array(0,1,2,3,4,5,6,7,8,9,10);
$rand = mt_rand(0,10);
for ($i = 0; $i < 8; $i++)
{
echo $array[$rand]." ";
$rand = mt_rand(0,10);
}
?>

 

 

The result will always random, here is my result :

2 3 1 4 5 5 2 8

 

The question is : How to make a unique result for each number, I do not want the same number show up again like number 2 and 5.

 

I want to have this result :

 

0 8 4 9 6 5 7 3 or

7 6 4 8 5 10 1 0 or

4 9 7 10 3 2 0 5

(random number but each one is unique doesn't appear twice or more)

 

How to do it? Thank you.

Link to comment
https://forums.phpfreaks.com/topic/114049-solved-how-to-generate-unique-number/
Share on other sites

the best way i have found on how to do this is to put the generated numbers in an array

<?php
$rand = array();

for ($i = 0; $i < 8; $i++)
{
    $number = mt_rand(0,10);
    while(array_search($number,$rand)===false){
        $number = mt_rand(0,10);
    }
    echo $number . " ";
}
?>

Scott.

Thanks for the reply, but it's still not working

 

<?
$rand = array(0,1,2,3,4,5,6,7,8,9,10);

for ($i = 0; $i < 8; $i++)
{
    $number = mt_rand(0,10);
    while(array_search($number,$rand)===false){
        $number = mt_rand(0,10);
    }
    echo $number . " ";
}
?>

 

The results :

 

2 8 1 5 1 4 8 1      - 1rst

2 10 5 4 5 4 5 5    - 2nd

8 10 5 8 8 5 0 2    - 3th

 

Still, no unique number in each result

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.