Q:

Write a PHP function to shuffle an associative array, preserving key, value pairs

0

Write a PHP function to shuffle an associative array, preserving key, value pairs

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

<?php
function shuffle_assoc($my_array)
	{
        $keys = array_keys($my_array);

        shuffle($keys);

        foreach($keys as $key) {
            $new[$key] = $my_array[$key];
        }

        $my_array = $new;

        return $my_array;
    }

$colors = array("color1"=>"Red", "color2"=>"Green", "color3"=>"Yellow");

print_r(shuffle_assoc($colors));
?>

Sample Output:

Array                                                       
(                                                           
    [color1] => Red                                         
    [color2] => Green                                       
    [color3] => Yellow                                      
)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now