Mithil Bhoras
Mithil Bhoras

Reputation: 349

array_rand not working as expected in PHP

I was playing around with PHP as I've just begun my training in it. I came across the array_rand function that returns random indexes and you can control how many random indexes you want. But what if the number of random indexes is kept equal to the actual length of the array? I tried it and the result was surprising.

<?php
$arr = array(1,2,3,4,5,6);
$temp = array_rand($arr,6);
foreach($temp as $r){
    echo $arr[$r]." ";
}
?>

So, I'm randomizing all the indices and printing the same array once again, but in the order that array_rand returns. Please note that I'm not looking for an alternative for this piece of code as I was solely practicing. What I want to know is why the random function returns Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 ) [if you print the array_rand result]? Why is it not random in this case?

Upvotes: 3

Views: 1329

Answers (2)

Mohamed Abulnasr
Mohamed Abulnasr

Reputation: 597

Just add one more step after arry_rand, shuffle(); so your code will be:

<?php
$arr = array(1,2,3,4,5,6);
$temp = array_rand($arr,6);
shuffle($temp);
foreach($temp as $r){
    echo $arr[$r]." ";
}
?>

because as pre. answer explained the mean.

Upvotes: 1

John Fonseka
John Fonseka

Reputation: 795

array_rand is to pick some random indexes from a given array. For example it may gives you 1,3,4 indexes or 3,5,6 indexes. But not 5,2,4 (At least the purpose of the function is not that).

If you want to randomize indexes for an array you have to use shuffle

http://php.net/manual/en/function.shuffle.php

Upvotes: 4

Related Questions