How to use random () function to shuffle array in PHP -
in 1 interview asked shuffle associative array has value .
$card = array ( "car"=>1, "bus"=>2, "truck"=>3, );
etc. using radom function generate random digit between 0,1
;
they asked me not use inbuilt php function .
input: associative array; output: randomly sequenced associative array;
thanks & regards
the built-in shuffle()
doesn't handle associative arrays well, you'd need shuffle array keys , reconstitute array again.
i'm using fisher-yates-knuth algorithm perform shuffling, crux of solution.
function myshuffle($arr) { // extract array keys $keys = []; foreach ($arr $key => $value) { $keys[] = $key; } // shuffle keys ($i = count($keys) - 1; $i >= 1; --$i) { $r = mt_rand(0, $i); if ($r != $i) { $tmp = $keys[$i]; $keys[$i] = $keys[$r]; $keys[$r] = $tmp; } } // reconstitute $result = []; foreach ($keys $key) { $result[$key] = $arr[$key]; } return $result; }
Comments
Post a Comment