Home >Backend Development >PHP Problem >How to make array output randomly in php

How to make array output randomly in php

PHPz
PHPzOriginal
2023-04-26 09:13:241259browse

In PHP, if we want to randomly output an array, we can use the shuffle() function and array_rand() function to achieve this.

The shuffle() function can shuffle the order of the array, and the array_rand() function can randomly return one or more key values ​​in the array.

Let’s introduce the specific implementation method:

Method 1: Use the shuffle() function

The shuffle() function can randomly disrupt the order of the array. The code is as follows:

<?php
//定义一个数组
$arr = array(&#39;apple&#39;,&#39;banana&#39;,&#39;orange&#39;,&#39;strawberry&#39;,&#39;kiwi&#39;);

//打乱数组顺序
shuffle($arr);

//循环输出数组元素
foreach($arr as $value){
    echo $value.&#39;<br>';
}
?>

In the above code, we first define an array $arr, which contains 5 fruit names. Then use the shuffle() function to shuffle the order of the array. Finally use a foreach loop to iterate through the array and output each element.

Method 2: Use array_rand() function

array_rand() function can randomly return one or more key values ​​in the array, the code is as follows:

<?php
//定义一个数组
$arr = array(&#39;apple&#39;,&#39;banana&#39;,&#39;orange&#39;,&#39;strawberry&#39;,&#39;kiwi&#39;);

//随机返回数组中一个元素的键值
$key = array_rand($arr,1);

//输出该元素的值
echo $arr[$key];
?>

In the above code , we first defined an array $arr, which contains 5 fruit names. Then use the array_rand() function to randomly return the key value of an element in the array. Finally, the value of the element is output.

It should be noted that using the array_rand() function will return the key value of the element, not the specific value. We need to use the key value again to extract the value of the element and output it.

To sum up, whether you use the shuffle() function or the array_rand() function, you can easily achieve random output of an array in PHP.

The above is the detailed content of How to make array output randomly in php. 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