Home > Backend Development > PHP Problem > How to find the maximum and minimum value of a php array

How to find the maximum and minimum value of a php array

青灯夜游
Release: 2023-03-15 21:38:02
Original
6869 people have browsed it

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.

How to find the maximum and minimum value of a php array

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(&#39;content-type:text/html;charset=utf-8&#39;);   
$arr=array(1,2,3,4,5,6,7,8,9);
echo "数组最大值为: ".max($arr)."<br>";
echo "数组最小值为: ".min($arr)."<br>";
?>
Copy after login

How to find the maximum and minimum value of a php array

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);
?>
Copy after login

How to find the maximum and minimum value of a php array

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

  • ##array_key_first() to get the first element of the specified array. A key value.

  • array_key_last() Gets the last key value of the specified array.

  • echo "数组最大值为: ".array_key_last($arr)."<br>";
    echo "数组最小值为: ".array_key_first($arr)."<br>";
    Copy after login

    How to find the maximum and minimum value of a php array

    Note: PHP versions of these two functions: PHP 7 >= 7.3.0, PHP 8

    recommended Study: "

    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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template