user3796133
user3796133

Reputation: 348

array_rand returning same value

I am having a problem returning random array keys if the specified number of entries is the same as the number of items in the array.

$rdm = array_rand($similar_product_array, 4);

will always return key values 0, 1, 2, 3 if there is 4 items in the array.

for example:

// Items in array
array (size=4)
  0 => string 'Batman Heroes Edition Nendoroid' (length=31)
  1 => string 'Oberyn' (length=6)
  2 => string 'White Walker' (length=12)
  3 => string 'Avengers Age of Ultron Hulk' (length=27)

// "randomly" generated array keys is always 0 , 1, 2, 3
array (size=4)
  0 => int 0
  1 => int 1
  2 => int 2
  3 => int 3

however, if i have:

$rdm = array_rand($similar_product_array, 3);

// Returns randomly as expected
array (size=3)
  0 => int 0
  1 => int 2
  2 => int 3

it will return randomly generated keys as it should.

What could i be doing wrong here?

Upvotes: 0

Views: 1521

Answers (1)

Miro
Miro

Reputation: 1899

You misunderstood purpose of array_rand() function, it is supposed to give you random entries from array, but not in random order. That means that if you are asking for 4 random items from array with 4 items, it will always return all the items (in the original order).

If you just need to change randomly the order of array entries, use shuffle() function, for example in this way:

$array_copy = $array;
shuffle($array_copy);
$rdm = array_rand($array_copy, <how_many_you_need>);

Upvotes: 6

Related Questions