Thursday, 30 August 2018

Php, how to twin / random the order of the associative array while keeping the key / value pairs

What is the php function to randomize the associative array while keeping key/values pairs. I don't mean to just randomly pick out a key value pair, but actually changing the array (similar to the uasort function, but not in order).

TIA
example:
original array
(
    [a] => 4
    [b] => 8
    [c] => -1
    [d] => -9
    [e] => 2
    [f] => 5
    [g] => 3
    [h] => -4
)

random ordered array
(

[d] => -9
[a] => 4
[b] => 8
[c] => -1
[h] => -4
[e] => 2
[g] => 3
[h] => -4
[f] => 5
)

Edit Comparison between 2 solutions.
$start = microtime(true);
$array = array('a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4);
$shuffleKeys = array_keys($array);
shuffle($shuffleKeys);
$newArray = array();
foreach($shuffleKeys as $key) {
    $newArray[$key] = $array[$key];
}
print_r ($newArray);
$elapsed = microtime(true) - $start;
echo "<br>array values took $elapsed seconds.<br>";

$start = microtime(true);
$array = array('a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4);
$keys = array_keys( $array );
   shuffle( $keys );
   print_r(array_merge( array_flip( $keys ) , $array ));

$elapsed = microtime(true) - $start;
echo "<br>array values took $elapsed seconds.<br>";

Array ( [h] => -4 [e] => 2 [b] => 8 [d] => -9 [a] => 4 [c] => -1 [f] => 5 [g] => 3 ) array values took 3.0994415283203E-5 seconds.
Array ( [e] => 2 [a] => 4 [d] => -9 [c] => -1 [g] => 3 [f] => 5 [b] => 8 [h] => -4 ) array values took 4.2915344238281E-5 seconds.

You could use shuffle() on array_keys, then loop around your array adding them to the list in the new order.
E.g.
$shuffleKeys = array_keys($array);
shuffle($shuffleKeys);
$newArray = array();
foreach($shuffleKeys as $key) {
    $newArray[$key] = $array[$key];
}

0 comments:

Post a Comment