w3resource

PHP Array Exercises : Shuffle an associative array, preserving key, value pairs


26. Shuffle Associative Array Preserving Keys

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:

Flowchart: PHP - Shuffle an associative array, preserving key, value pairs

For more Practice: Solve these Related Problems:

  • Write a PHP function to randomly shuffle an associative array while maintaining its key-value pairs.
  • Write a PHP script to create a new associative array by shuffling the keys but preserving the original key-value relationship.
  • Write a PHP program to implement a custom shuffle function for an associative array without losing its keys.
  • Write a PHP script to use a combination of array_keys() and shuffle() to reorder an associative array and then rebuild it.

Go to:


PREV : Sort Entity Letters.
NEXT : Generate Random Password Using Shuffle.

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.