Jimmy
Jimmy

Reputation: 78

Random array not working as the expected

I'm trying to create an array and display some random values. I'm using the following code:

$range = range(10,31);
$rand = array_rand($range,5);
shuffle($rand);

foreach ($rand as $number) {
  $number = (str_pad($number, 2, "0", STR_PAD_LEFT));
  echo $number." ";
} 

I want to generate numbers between 10 and 31 and display 5 of them, but my code still generating numbers between 00 and 31. Why this is happening?

Upvotes: 0

Views: 58

Answers (3)

Marco Acierno
Marco Acierno

Reputation: 14847

If you want to print 5 random numbers between 10 and 30 why not create a range of [10, 31] call shuffle on it, then print only 5 numbers?

$arr = range(10, 31);
shuffle($arr);
for ($i = 0; $i < 5; ++$i) {
echo $arr[$i] . "<br />";
}

Upvotes: 1

Barmar
Barmar

Reputation: 780787

Since array_rand() returns keys, not values, you have to use them as indexes into the original $range array.

foreach ($rand as $index) {
  $number = (str_pad($range[$index], 2, "0", STR_PAD_LEFT));
  echo $number." ";
}

You could also just call shuffle($range) and then iterate over the first 5 elements of $range.

Upvotes: 2

range creates an array from 10 to 31, assigning them from key [0] to [21]. array_rand returns the KEY of random entries. try this:

for ($1=10,$i<32,$i++)
 {$range[$i] = 1;}

that should give you an array with KEYS from 10 to 31, then it might work :)

Upvotes: 0

Related Questions