Home > Backend Development > PHP Problem > How to find the minimum value in an array in php

How to find the minimum value in an array in php

青灯夜游
Release: 2023-03-15 22:44:01
Original
5017 people have browsed it

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.

How to find the minimum value in an array in php

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

How to find the minimum value in an array in php

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

How to find the minimum value in an array in php

After sorting, the first element of the array is the minimum value, which can be taken out using the reset() function.

echo "数组最小值为: ".reset($arr);
Copy after login

How to find the minimum value in an array in php

3. Sort in descending order and get the last element

Use rsort to sort the array in descending order

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$arr=array(52,1,45,9,0,21,2,40,42);
rsort($arr);
var_dump($arr);
?>
Copy after login

How to find the minimum value in an array in php

After sorting, the last element is the minimum value, which can be obtained using the end() function.

echo "数组最小值为: ".end($arr);
Copy after login

How to find the minimum value in an array in php

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!

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