Home >Backend Development >PHP Tutorial >php array shuffled order

php array shuffled order

王林
王林Original
2019-09-12 17:40:255131browse

php array shuffled order

shuffle()

PHP shuffle() function randomly arranges the order of array cells (shuffles the array). This function assigns new keys to the elements in the array. This will delete the original keys rather than just reorder them.

Syntax:

##bool shuffle ( array &array )

Example 1:

<?php
$arr = range(1,8);
print_r($arr);
echo &#39;<br />&#39;;
shuffle($arr);
print_r($arr);
?>

Output:

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 ) 
Array ( [0] => 6 [1] => 1 [2] => 3 [3] => 2 [4] => 5 [5] => 7 [6] => 8 [7] => 4 )

It should be noted that every time the page is refreshed, the print_r($arr) result after shuffle($arr) is different. . Since PHP 4.2.0, it is no longer necessary to use functions such as srand() to seed the random number generator and the system will automatically complete it.

Example 2: Using associative array

<?php
$arr = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
shuffle($arr);
print_r($arr);
?>

Output:

Array ( [0] => 5 [1] => 2 [2] => 1 [3] => 3 [4] => 4 )

Of course, the results output every time the page is refreshed are different.


The above content is for reference only!

Recommended video tutorial:

PHP video tutorial

The above is the detailed content of php array shuffled order. 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
Previous article:Convert php array to jsonNext article:Convert php array to json