PHP Array Exercises : Shuffle an associative array, preserving key, value pairs
Write a PHP function to shuffle an associative array, preserving key, value pairs.
Sample Solution:
PHP Code:
<?php
// Define a function to shuffle an associative array
function shuffle_assoc($my_array)
{
// Get the keys of the associative array
$keys = array_keys($my_array);
// Shuffle the keys
shuffle($keys);
// Initialize an empty array to store the shuffled associative array
$new = array();
// Iterate through the shuffled keys
foreach ($keys as $key) {
// Assign each key-value pair to the new array in shuffled order
$new[$key] = $my_array[$key];
}
// Update the original array with the shuffled result
$my_array = $new;
// Return the shuffled associative array
return $my_array;
}
// Define an associative array of colors
$colors = array("color1" => "Red", "color2" => "Green", "color3" => "Yellow");
// Call the shuffle_assoc function and print the result
print_r(shuffle_assoc($colors));
?>
Output:
Array ( [color1] => Red [color2] => Green [color3] => Yellow )
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP function to sort entity letters.
Next: Write a PHP function to generate a random password (contains uppercase, lowercase, numeric and other) using shuffle() function.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics