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

WBOY
Release: 2024-05-03 10:09:01
Original
517 people have browsed it

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 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'];
Copy after login

Then we can get a shuffled array:

shuffle($original);
Copy after login
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'];
Copy after login

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!