Home  >  Article  >  Backend Development  >  How to find the maximum value in an array in php

How to find the maximum value in an array in php

青灯夜游
青灯夜游Original
2022-05-07 15:17:227425browse

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.

How to find the maximum value in an array in php

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(&#39;content-type:text/html;charset=utf-8&#39;);   
$arr=array(52,1,45,9,0,21,-1,40,-5);
var_dump($arr);
echo "数组最大值为: ".max($arr)."<br>";
?>

How to find the maximum value in an array in php

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);

How to find the maximum value in an array in php

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);

How to find the maximum value in an array in php

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!

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
Previous article:What does as mean in phpNext article:What does as mean in php