Daniel
Daniel

Reputation: 2501

PHP - random with current keys

If I have this code:

array(0 => "hey", 1 => "bla", 2 => "test", 3 => "ag")

And I want to rand it, but with the current keys:

array(2 => "test", 0 => "hey", 3 => "ag", 1 => "bla");

How can I do that?

Upvotes: 2

Views: 70

Answers (1)

Paul
Paul

Reputation: 141877

Here's a function you can use if you want:

function pkey_shuffle($arr){
    $keys = array_keys($arr); 
    shuffle($keys); 
    $new = array();
    $count = count($keys);
    for($i = 0; $i < $count; $i++){
        $new[$keys[$i]] = $arr[$keys[$i]];
    }
    return $new;
}

$arr = array(2 => "test", 0 => "hey", 3 => "ag", 1 => "bla");
print_r($arr);
echo '<br />';
print_r(pkey_shuffle($arr));

Upvotes: 3

Related Questions