0

I need 9 unique random numbers between 0 and 44. I create an array with range to add numbers between 0 and 44 and then I use shuffle like this:

$buildingIdArray  = array();
$numbers = range (0, $maxNumberOfBuildings);
shuffle($numbers);

I need some help to complete the code. I want to pick the 9 numbers by the arrays index, should I just use a loop to get the numbers of the index between 0 and 8 or should i use slice to pick numbers and then remove that index?

I want to add the 9 unique numbers in the array $buildingIdArray. Any idea how to solve this?

3 Answers 3

2

array_slice() is a good choice in this application.

$buildingIdArray  = array();
$numbers = range (0, $maxNumberOfBuildings);
shuffle($numbers);
$buildingIdArray=array_slice ($numbers,0,9);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but I have some problems with the code! It's not working! Please have a look at my other question: stackoverflow.com/questions/17071881/loop-mysql-result
I found the error now! In line 4 there is a ';' missing!!! I copied the code above, and since there was no ';' it didn't work!
I see. I've added a semicolon to the end of the line.
1

If you are picking only one entry, array_rand() returns the key for a random entry. Otherwise, it returns an array of keys for the random entries. This is done so that you can pick random keys as well as values out of the array.

$rand_key = array_rand($buildingIdArray);
echo $buildingIdArray[$rand_key] . "\n";

Comments

1
$buildingIdArray  = array();
$numbers = range (0, $maxNumberOfBuildings);
shuffle($numbers);
for($i=0;$i<9;$i++) {
    $buildingIdArray[] = $numbers[$i];
}

2 Comments

It should be $buildingIdArray[] = $number[$i], php's arrays are not really objects, are they?
Yep you are right. Been working with objects all day today :)

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.