How to shuffle an array while preserving keys in php, wordpress

In PHP (including WordPress), you can shuffle an array while preserving its keys by using a custom function. The standard shuffle() function resets the array keys, so you need a different approach.

Here’s one way to shuffle an array while preserving its keys:

function shuffle_assoc($array) {
    if (!is_array($array)) {
        return $array;
    }

    // Get the keys of the array
    $keys = array_keys($array);

    // Shuffle the keys
    shuffle($keys);

    // Create a new array with shuffled keys
    $shuffled = [];
    foreach ($keys as $key) {
        $shuffled[$key] = $array[$key];
    }

    return $shuffled;
}

// Example usage
$my_array = [
    'one' => 1,
    'two' => 2,
    'three' => 3,
    'four' => 4
];

$shuffled_array = shuffle_assoc($my_array);
print_r($shuffled_array);

This shuffle_assoc() function first extracts the array keys, shuffles them using shuffle(), and then constructs a new array with the shuffled keys, preserving the key-value association but in random order.

How useful is the publication?

Click on a star to rate it!

Average score 5 / 5. Number of grades: 1

No ratings yet. Rate it first.

Similar posts

How to exclude posts with parent post in wp_query, WordPress

To exclude posts that have a parent (i.e., child posts) in a WP_Query request, you can use the post_parent argument. This argument controls whether the post has a parent or not. To exclude child posts, set the condition post_parent => 0, which means that only top-level posts (posts without a parent) will be included in…
Read more