Home  >  Article  >  Backend Development  >  How to scramble the array in php and randomly select several array elements

How to scramble the array in php and randomly select several array elements

青灯夜游
青灯夜游Original
2021-11-29 14:21:273582browse

Method: 1. Use shuffle() to randomly shuffle the array; 2. Use array_rand() to randomly obtain multiple key names from the array and return an array of key names; 3. Use the foreach statement to traverse the key name array , get the value from the disordered array according to the obtained key name, and assign it to a new array; 4. Output the new array after the traversal is completed.

How to scramble the array in php and randomly select several array elements

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

php disrupts the array Randomly select several array elements

To disrupt the array, you can use the shuffle() function

To randomly select array elements: you can use the array_rand() function and the foreach statement

  • array_rand() function returns the random key name in the array. The array_rand() function accepts two parameters: the first parameter $array specifies the array, and the second parameter $number specifies the number of key names to be obtained.

  • When the array_rand() function obtains multiple key names, it will return an array $rands containing random key names.

  • In this way, we can use the foreach statement to traverse the $rands array, continuously take the value from the $arr array based on the key name in the $rands array, and assign it to the new array $arr2 That’s it.

Implementation code:

<?php
$arr=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
shuffle($arr);
$rand = array_rand($arr,3);
foreach($rand as $val){
	$arr2[$val]=$arr[$val];
}
var_dump($arr2);
?>

How to scramble the array in php and randomly select several array elements

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to scramble the array in php and randomly select several array elements. 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