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

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -