3D-kreativ
3D-kreativ

Reputation: 9319

Select random values from array

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?

Upvotes: 0

Views: 122

Answers (3)

IanPudney
IanPudney

Reputation: 6031

array_slice() is a good choice in this application.

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

Upvotes: 2

RST
RST

Reputation: 3925

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

Upvotes: 1

RTB
RTB

Reputation: 5833

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";

Upvotes: 1

Related Questions