Home  >  Article  >  Backend Development  >  How to find the third smallest value of an array in php

How to find the third smallest value of an array in php

青灯夜游
青灯夜游Original
2022-05-16 11:47:342127browse

Method: 1. Use array_values() to convert the array into an index array, the syntax is "array_values ​​(original array)"; 2. Use sort() to sort the array in ascending order, the syntax is "sort(index array)" , at this time the element with index 2 is the third smallest value; 3. Use the "index array name [2]" statement to obtain.

How to find the third smallest value of an array in php

The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer

php to find the array number Method of three small values

In PHP, sort the array in ascending order, so that the small value comes first, the large value comes last, and the first three values ​​(a[0], a [1], a[2]) are the first, second, and third smallest values. Just take out the element with index 2 (a[2]).

The following are the specific steps.

1. Convert the array to an index array

Use array_values() to obtain the values ​​of all elements in the array. You can convert the associative array into an index array to ensure that the array is Index array. (In this way, the index value can be used to extract the third smallest value later).

<?php
header("Content-type:text/html;charset=utf-8");
$arr=array("a"=>44,"b"=>23,"c"=>56,"d"=>2,"e"=>9,"f"=>1,"g"=>8,"h"=>-1);
var_dump($arr);
$value=array_values($arr);
var_dump($value);
?>

How to find the third smallest value of an array in php

2. Sort the index array in ascending order

Use the sort() function to sort the array in ascending order, so that the array elements Sort from small to large.

sort($value);
var_dump($value);

How to find the third smallest value of an array in php

At this time, the third element at the beginning, that is, the one with index 2 is the third smallest value required.

3. Get the third smallest value

Just use the "array name [2]" form to get the third element after sorting.

echo "数组第三小值为:".$value[2];

How to find the third smallest value of an array in php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to find the third smallest value of 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