Home > Article > Backend Development > How to find the maximum value in an array in php
Two methods: 1. Use max() to get the maximum value, the syntax is "max($arr)". 2. Use "arsort($arr)" to sort the array in descending order. After sorting, the first element of the array is the maximum value. Use "reset($arr)" or "array_key_first($arr)" to take it out.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php seeks the array Two methods of maximum value
Method 1: Directly use the built-in function max()
max() function can return an array Maximum value
<?php header('content-type:text/html;charset=utf-8'); $arr=array(52,1,45,9,0,21,-1,40,-5); var_dump($arr); echo "数组最大值为: ".max($arr)."<br>"; ?>
Method 2: Sort the array elements in descending order and take out the first element
Use arsort() to Sort the array in descending order
$arr=array(52,1,45,9,0,21,-1,40,-5); arsort($arr); var_dump($arr);
Then the first element of the array is the required maximum value, just take it out.
To get the first element, you can use the reset() or array_key_first() function.
array_key_first() Get the first key value of the specified array.
#reset() function can point the internal pointer in the array to the first element and return the value of the first array element. If the array is empty, it returns a Boolean value False.
echo "数组最大值为: ".reset($arr)."<br>"; echo "数组最大值为: ".array_key_first($arr);
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to find the maximum value in an array in php. For more information, please follow other related articles on the PHP Chinese website!