Home > Article > Backend Development > How to find the minimum value in an array in php
3 methods: 1. Use "min($arr)" to obtain. 2. Use "sort($arr)" to sort in ascending order. After sorting, the first element is the minimum value, and use "reset($arr)" to obtain it. 3. Use "rsort($arr)" to sort in descending order, and use "end($arr)" to get the last element.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php seeks the smallest array Value method
In PHP, if you want to get the minimum value of an array, you can directly use the built-in function min();
You can also sort the array elements, If it is sorted in descending order, get the last element, if it is sorted in ascending order, get the first element.
Let’s take a closer look
1. Use the min() function
The min() function returns the minimum value in an array
<?php header('content-type:text/html;charset=utf-8'); $arr=array(1,2,3,4,5,6,7,8,9); var_dump($arr); echo "数组最小值为: ".min($arr); ?>
2. Sort in ascending order and get the first element
You can use sort() to sort the array in ascending order
<?php $arr=array(52,1,45,9,0,21,2,40,42); sort($arr); var_dump($arr); ?>
After sorting, the first element of the array is the minimum value, which can be taken out using the reset() function.
echo "数组最小值为: ".reset($arr);
3. Sort in descending order and get the last element
Use rsort to sort the array in descending order
<?php header('content-type:text/html;charset=utf-8'); $arr=array(52,1,45,9,0,21,2,40,42); rsort($arr); var_dump($arr); ?>
After sorting, the last element is the minimum value, which can be obtained using the end() function.
echo "数组最小值为: ".end($arr);
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to find the minimum value in an array in php. For more information, please follow other related articles on the PHP Chinese website!