Home >Backend Development >PHP Tutorial >How to get a random array list in php PHP custom function to get a random array

How to get a random array list in php PHP custom function to get a random array

WBOY
WBOYOriginal
2016-07-25 08:51:211025browse
  1. function create_random_ids( $min,$max,$limited )
  2. {
  3. $_base_ids = range($min,$max);
  4. $_temp_key = array_rand ($_base_ids,min(count($_base_ids),$ limited+10));
  5. //Splicing
  6. $ids = array();
  7. for ($x=0; $x < count($_temp_key); $x++) {
  8. $ids[] = $_base_ids[$ _temp_key[$x]];
  9. }
  10. return $ids;
  11. }
Copy code
2. Usage of PHP array random extraction functions shuffle() and array_rand() In PHP, random extraction of PHP arrays can be done using the shuffle() and array_rand() functions. Random extraction is to scramble the elements of the original array and output them. After each execution, the order or elements of the extraction are different. This function can be used to display different advertisements on the web page each time. Use the shuffle() function to achieve randomization of the array. Extraction:
  1. $textArray = array('1','2','3','4','5','6','7');
  2. shuffle($ textArray);
  3. print_r($textArray);
  4. ?>
Copy code
Result: Array ( [0] => 6 [1] => 3 [2] => 7 [3] => 4 [4] => 1 [5] => 2 [6] => 5 ) Implemented random ordering of array elements; PHP also provides a function for randomly extracting values ​​from an array: array_rand(). Its calling format is as follows: array_rand(,[number of extracted elements]);
  1. $arry = array('A','B','C','D');
  2. $result = array_rand ($arry,2);
  3. foreach ($result as $val) {
  4. echo $arry["$val"].""; }
  5. ?>
Copy code
Result: B C Refreshing has different results;


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