Home > Article > Backend Development > How to find the subscript of the largest number in an array in php
Implementation steps: 1. Use the max() function to obtain and return the maximum number of the array, with the syntax "max(array)"; 2. Use the array_search() function to search for the maximum number in the array and return the corresponding next Just mark (key name), the syntax is "array_search (maximum number, array)".
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
In php, you can use the max() function and array_search() function to find the subscript of the largest number in the array.
Implementation steps:
Step 1: Use the max() function to find the maximum number of the array
max() function Returns the maximum value in an array, or the maximum value among several specified values.
<?php header('content-type:text/html;charset=utf-8'); $arr=array("1"=>5,"8"=>7,"3"=>4,"7"=>5,"6"=>5); var_dump($arr); $max=max($arr); echo "最大数为:".$max; ?>
Step 2: Use the array_search() function to get the subscript (key name) of the maximum value
<?php header('content-type:text/html;charset=utf-8'); $arr=array("1"=>5,"8"=>7,"3"=>4,"7"=>5,"6"=>5); var_dump($arr); $max=max($arr); echo "最大数为:".$max."<br>"; $res=array_search($max,$arr); echo "最大数的下标为:".$res; ?>
Description:
array_search() function searches for a key value in the array and returns the corresponding key name.
array_search(value,array,strict)
Parameters | Description |
---|---|
value | Required . Specifies the key value to search for in the array. |
array | Required. Specifies the array to be searched. |
strict | Optional. If this parameter is set to TRUE, the function searches the array for elements of the same data type and value. Possible values:
|
Return value:
If the specified key value is found in the array, return the corresponding key name, otherwise return FALSE. If a key value is found more than once in the array, the key name matching the first found key value is returned.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to find the subscript of the largest number in an array in php. For more information, please follow other related articles on the PHP Chinese website!