Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to disrupt the array and select several array elements randomly by php

2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains how php disrupts the array and selects several array elements at random. Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how php disrupts the array and selects several array elements at random.

Methods: 1, use shuffle () to randomly disrupt the array; 2, use array_rand () to randomly get multiple key names from the array, return an array of key names; 3, use foreach statements to traverse the array of key names, take values from the disordered array according to the key names obtained, and assign values to a new array; 4, output the new array after traversal.

Operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

Php disrupts the array and randomly selects several array elements.

You can use the shuffle () function to scramble an array

Randomly select array elements: you can use the array_rand () function and foreach statements

The array_rand () function returns random key names in the array. The array_rand () function takes two arguments: the first argument, $array, specifies the array, and the second parameter, $number, specifies the number of key names to get.

When the array_rand () function gets multiple key names, it returns an array of random key names, $rands.

This allows us to use the foreach statement to iterate through the $rands array, constantly taking values from the $arr array based on the key names in the $rands array, and assigning values to the new array $arr2.

Implementation code:

At this point, I believe you have a deeper understanding of "how php disrupts the array and randomly selects several array elements". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report