Home  >  Article  >  Backend Development  >  How to retain the index of original elements after shuffling PHP array?

How to retain the index of original elements after shuffling PHP array?

WBOY
WBOYOriginal
2024-05-03 10:09:01543browse

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.

How to retain the index of original elements after shuffling PHP array?

PHP retains the original index after shuffling the order of the array

PHP provides the shuffle() 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'];

Then we can get a shuffled array:

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 the

shuffle() function to shuffle it Element:

$shuffled = ['baz', 'bar', 'foo'];

Method 2: Use ksort()

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);

Both of the above two methods can preserve the original index, but method 1 is simpler, while method 2 is more general.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn