-1

I am trying to generate 6 numbers in an array, I'm using the mt_rand function, however I can't have the same number in the array. How would I go about checking for this and generating the number again?

I've thought about making a duplicate array and looping throw and counting how many are in the array, if its more then 1 then re generating the numbers and checking again, however this just seems like a lot of work for something that php might have a native function for that I can't find...

The duplicate thing isn't what I need help with, that is checking the key to the value, I need all values to be unique.

4
  • Possible duplicate of Generate array of random unique numbers in PHP Commented Jul 29, 2016 at 16:32
  • This isn't the same thing, that is to make sure the key and value aren't the same. I need just values. Commented Jul 29, 2016 at 16:35
  • 1
    This one most certainly is a better duplicate: stackoverflow.com/questions/7792816/… Commented Jul 29, 2016 at 16:38
  • 1
    Welcome to Stack Overflow! If this question is not a duplicate of the second question that @Laurel posted, please provide more information to explain how it is different. Also, to make it easier for other users to help you, please include some code to show what you have tried, preferably in the form of a minimal reproducible example. See also How to Ask. Commented Jul 29, 2016 at 16:51

1 Answer 1

0
$number_of_numbers = 6;//number_of_numbers in array
$min = 1;//minimum value of number that you want
$max = 15;//maximum value of number that you want

$array = array();
for ($a = 0; $a < $number_of_numbers; $a++) {
    $check = 0;//for entering while loop
    while ($check !== false) { //pick a number and check if it is in array if it is in the array, pick again and check again
        $try[$a] = mt_rand($min, $max); //pick a number
        $check = array_search($try[$a], $array);// search that number if it is in the array
    }
    $array[] = $try[$a]; //add number to array
}
var_dump($array); // show me the array

Is that what you mean? I may get misunderstood about the array keys. Can you explain it a little more?

here is the output. sorry i forgot to add it first.

array(6) { [0]=> int(10) [1]=> int(12) [2]=> int(3) [3]=> int(5) [4]=> int(9) [5]=> int(15) }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.