Two methods: 1. Use the "max(array)" statement to obtain the maximum value, and use the "min(array)" statement to obtain the minimum value. 2. Use "sort(array)" to sort the array in ascending order, use "array_key_first(array)" to get the minimum value, and "array_key_last(array)" to get the maximum value.
The operating environment of this tutorial: windows7 system, PHP7.5 version, DELL G3 computer
In php, there are many ways to obtain For the maximum and minimum values of the array, this article will introduce two methods to you:
Method 1: Use the max() and min() functions
max() function returns the maximum value in an array
min() function returns the minimum value in an array
Example:
<?php header('content-type:text/html;charset=utf-8'); $arr=array(1,2,3,4,5,6,7,8,9); echo "数组最大值为: ".max($arr)."<br>"; echo "数组最小值为: ".min($arr)."<br>"; ?>
Method 2: Use sort(), array_key_first(), array_key_last() functions
You can use sort() to sort the array in ascending order
<?php $arr=array(52,1,45,9,0,21,-1,40,-5); sort($arr); var_dump($arr); ?>
It can be seen that the first element of the array is the minimum value, and the last element is the maximum value. Just take out these two values.
So how to get the first element and the last element of the array? You can use the array_key_first() and array_key_last() functions
echo "数组最大值为: ".array_key_last($arr)."<br>"; echo "数组最小值为: ".array_key_first($arr)."<br>";
PHP Video Tutorial"
The above is the detailed content of How to find the maximum and minimum value of a php array. For more information, please follow other related articles on the PHP Chinese website!