php in order to make an array of random, out of sequence, etc.

There are many php sorting function, sort, rsort, ksort, krsort, asort, arsort, natcasesort, these function keys or values ​​used to perform such an array, or another sort.

After all, sometimes you may also need some function to get random elements of the array.

array_rand () function

Obtaining a random function array, the number of elements can be specified once acquired by the second parameter, the first parameter target array

Note: this is just a random pseudo-random number

Example 1

1 $arr = [1, 2, 3, 4, 5];
2 print( array_rand( $arr, 6 ) );

Output:

Warning: array_rand(): Second argument has to be between 1 and the number of elements in the array in D:\workspace\project_shop\demo.php on line 3

In fact, it echoes nothing output, only a warning, the second parameter must be less than $ arr equal to the number of array elements.

Examples 2 normal usage, returns an array.

1 $arr = [1, 2, 3, 4, 5];
2 print_r( array_rand( $arr, 3 ) ) ;
3 // Array
4 // (
5 //     [0] => 0
6 //     [1] => 1
7 //     [2] => 2
8 // )

shuffe () function element position, disrupting the array

This function is passed a target array by reference, return truth value

Example 3 can be seen from the results, then upset the order of the elements position, did not retain the original key relationship

 1 $arr = [1, 2, 3, 4, 5];
 2 var_dump( shuffle( $arr ) ) ;
 3 print_r( $arr );
 4 // bool(true)
 5 // Array
 6 // (
 7 //     [0] => 3
 8 //     [1] => 4
 9 //     [2] => 2
10 //     [3] => 1
11 //     [4] => 5
12 // )

Guess you like

Origin www.cnblogs.com/zxcv123/p/11822790.html