PHP shuffle() function can shuffle the order of array elements, but the original index will not be preserved. Indexes can be preserved by: 1. Creating a new array and shuffling the elements; 2. Sorting the shuffled array using the ksort() function.
PHP retains the original index after shuffling the order of the array
PHP provides theshuffle()
function, You can randomly shuffle the order of elements in an array. However, it should be noted that this function only shuffles the order of elements and does not preserve the original index.
Practical case:
## Shuffle the order:$original = ['foo', 'bar', 'baz'];
shuffle($original);
Now, if we want to retain the original index, we can use the following method:
Method 1: Create a new array
We can first create a new array with the original index, and then use theshuffle()function to shuffle it Element:
$shuffled = ['baz', 'bar', 'foo'];
Method 2: Useksort()
ksort()
The function can pair the Arrays are sorted. We can use this feature to preserve the original index:
$newArray = array_values($original); shuffle($newArray);
The above is the detailed content of How to retain the index of original elements after shuffling PHP array?. For more information, please follow other related articles on the PHP Chinese website!