-
- function create_random_ids( $min,$max,$limited )
- {
- $_base_ids = range($min,$max);
- $_temp_key = array_rand ($_base_ids,min(count($_base_ids),$ limited+10));
- //Splicing
- $ids = array();
- for ($x=0; $x < count($_temp_key); $x++) {
- $ids[] = $_base_ids[$ _temp_key[$x]];
- }
- return $ids;
- }
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: - $textArray = array('1','2','3','4','5','6','7');
- shuffle($ textArray);
- print_r($textArray);
- ?>
-
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]);
-
- $arry = array('A','B','C','D');
- $result = array_rand ($arry,2);
- foreach ($result as $val) {
- echo $arry["$val"].""; }
- ?>
-
Copy code
Result:
B
C
Refreshing has different results; |