Home > php教程 > php手册 > body text

PHP 将数组打乱 shuffle函数的用法及简单实例,打乱shuffle

WBOY
Release: 2016-07-06 14:24:49
Original
1476 people have browsed it

PHP 将数组打乱 shuffle函数的用法及简单实例,打乱shuffle

shuffle()

PHP shuffle() 函数随机排列数组单元的顺序(将数组打乱)。本函数为数组中的单元赋予新的键名,这将删除原有的键名而不仅是重新排序。

语法:

bool shuffle ( array &array )

例子1:

<&#63;php
$arr = range(1,8);
print_r($arr);
echo '<br />';
shuffle($arr);
print_r($arr);
&#63;>
Copy after login

运行该例子输出:

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 ) 
Copy after login

需要说明的是,每次刷新页面,shuffle($arr) 后的 print_r($arr) 结果都是不一样的。而自 PHP 4.2.0 起,也不再需要用 srand() 等函数给随机数发生器播种而由系统自动完成。

例子2,使用关联数组:

<&#63;php
$arr = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
shuffle($arr);
print_r($arr);
&#63;>
Copy after login

运行该例子输出:

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

当然,每次刷新页面输出的结果都是不一样的。

以上就是小编为大家带来的PHP 将数组打乱 shuffle函数的用法及简单实例全部内容了,希望大家多多支持帮客之家~

Related labels:
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 Recommendations
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!