mardi 3 mai 2016

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?




Aucun commentaire:

Enregistrer un commentaire