PHP editor Xinyi introduces you to an interesting array operation method-shuffle the array and retain the key names. In PHP, random arrangement of array elements can be easily achieved through the shuffle function, but the indexes will be reassigned. If you want to retain the original key names, you can first use the array_keys function to obtain the key name array, then scramble it together with the value array, and finally recombine it into a new array through the array_combine function. In this way, you can achieve random arrangement of array elements while retaining the key names!
PHP shuffle the array and keep the key names
In php, use the shuffle()
function to shuffle the order of the array, but the key names will not be preserved. To preserve key names, you can use the following method:
Method 1: Use array_rand()
$array = ["a" => 1, "b" => 2, "c" => 3]; $keys = array_rand($array); $shuffled_array = []; foreach ($keys as $key) { $shuffled_array[$key] = $array[$key]; }
Method 2: Use mt_rand()
$array = ["a" => 1, "b" => 2, "c" => 3]; $keys = array_keys($array); shuffle($keys); $shuffled_array = []; foreach ($keys as $key) { $shuffled_array[$key] = $array[$key]; }
Method 3: Using third-party libraries
Third-party libraries, such as ArrayLib
, provide a more convenient way to shuffle arrays and retain key names:
use ArrayLibArrays; $array = ["a" => 1, "b" => 2, "c" => 3]; $shuffled_array = Arrays::shuffle($array);
Performance comparison
There are differences in the performance of these three methods:
array_rand()
Performs best with small arrays, but is less efficient with large arrays. mt_rand()
Performs well across all array sizes. scenes to be used
Disrupting the array and retaining key names is useful in the following scenarios:
Precautions
array_rand()
and mt_rand()
return a key, not a value. Need to use $array[$key]
to get the value. The above is the detailed content of PHP shuffles array, retaining key names. For more information, please follow other related articles on the PHP Chinese website!