PHP array function sequence shuffle() and array_rand() Introduction to the use of random functions_PHP tutorial

WBOY
Release: 2016-07-21 15:23:27
Original
1249 people have browsed it

shuffle() definition and usage
shuffle() function rearranges the elements in the array in random order.

Returns TRUE if successful, otherwise returns FALSE.

Note: This function assigns a new key name to the unit in the array. This will delete the original keys rather than just reorder them.

Note: As of PHP 4.2.0, it is no longer necessary to seed the random number generator with the srand() or mt_srand() functions, it is now done automatically.

Syntax
shuffle(array) Parameter Description
array Required. Specifies the array to use.

Example

Copy code The code is as follows:

$my_array = array ("a" => "Dog", "b" => "Cat", "c" => "Horse");
shuffle($my_array); print_r($my_array);
?>

Output:

Array ( [0] => Cat [1] => Horse [2] => Dog )

array_rand() definition and usage
array_rand() function randomly selects one or more elements from the array and returns it.

The second parameter is used to determine how many elements to select. If more than one element is selected, an array containing a random key is returned, otherwise the key of the element is returned.

Note: If the number of indexes extracted by the specified array_rand() function is greater than 1, then regardless of whether it is a numeric index array or an associative array, the key of the original array will be obtained and placed in a new index array middle.

Note: As of PHP 4.2.0, it is no longer necessary to seed the random number generator with the srand() or mt_srand() functions, it is now done automatically.

Syntax
array_rand(array,number) Parameter Description
array Required. Specifies the input array parameters.
number optional. The default is 1. Specifies how many random elements to return.

Example 1
Copy code The code is as follows:

$a= array("a"=>"Dog","b"=>"Cat","c"=>"Horse");
print_r(array_rand($a,1));
?>

Output:

b
Example 2
Array with string keys:
Copy Code The code is as follows:

$a=array("a"=>"Dog","b"=>"Cat" ,"c"=>"Horse");
print_r(array_rand($a,2));
?>

Output:

Array ( [0] => c [1] => b )

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324498.htmlTechArticleshuffle() definition and usage shuffle() function rearranges the elements in the array in random order. Returns TRUE if successful, FALSE otherwise. Note: This function is the unit in the array...
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
Popular Tutorials
More>
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!