Home  >  Article  >  Backend Development  >  PHP function example: Array random sorting

PHP function example: Array random sorting

王林
王林Original
2023-06-20 10:02:481276browse

Randomly sorted arrays are one of the common requirements in PHP language. For scenarios such as photo display and product display, randomly sorted arrays can enhance the interactivity and user experience of the page. Below, this article will use an example to explain how to implement random sorting of arrays through PHP functions.

We first define an array containing 5 elements, as shown below:

$products = array(
    "Apple",
    "Banana",
    "Orange",
    "Pineapple",
    "Watermelon"
);

Next, we will use PHP’s built-in shuffle() function to shuffle this array Sort randomly. shuffle() The function will randomly shuffle the elements of the array to achieve a random sorting effect. The code is as follows:

shuffle($products);

Now, the $products array has been randomly sorted, we can loop through the array through foreach and output the value of each element. The complete code is as follows:

$products = array(
    "Apple",
    "Banana",
    "Orange",
    "Pineapple",
    "Watermelon"
);

shuffle($products);

foreach ($products as $value) {
    echo "$value 
"; }

When we execute this code, it will output the following results:

Banana
Pineapple
Orange
Watermelon
Apple

As you can see, the elements of the array $products are typed If the order is messed up, the output results of each execution of the code will be different. In this way, we successfully implemented the need to randomly sort the array through PHP function instances.

In addition to the shuffle() function, PHP also provides some other functions to implement randomly sorted arrays, such as the array_rand() function. But unlike the shuffle() function, the array_rand() function will only return the randomly sorted key names, but not the randomly sorted values. If you want to return a value, you also need to call $array[$key] to get the value.

In general, it is very simple to implement randomly sorted arrays in PHP. You only need to call the built-in shuffle() function. Through this example, it is not difficult for us to find that the role of functions in the PHP language is very important, and can help developers realize some common operation requirements more efficiently.

The above is the detailed content of PHP function example: Array random sorting. 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