Implementation steps: 1. Use the foreach statement to traverse the array, the syntax is "foreach ($arr as $k=>$v){/loop body statement block}"; 2. In the loop body, use is_numeric () Get the numeric subscript and assign it to an empty array. The syntax "if(is_numeric($k)){$keys[]=$k;}" will get an array containing the numeric subscript; 3. Use min( ) Get the minimum value in the numeric subscript array, syntax "min($keys)".
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
In PHP, you can use the foreach statement and is_numeric () and min() functions to find the smallest numerical subscript in an array.
Implementation steps:
Step 1. Use the foreach statement to traverse the array
foreach ($array as $k => $v){ //循环体语句块; }
Traverse the given $arr array, and in each loop, the value of the current array will be assigned to $v, and the key name will be assigned to $k.
Step 2: In the loop body, use is_numeric() to obtain the numeric subscript and assign it to an empty array
is_numeric() Function is used to detect whether a variable is a number or a string of numbers. If the specified variable is a number or numeric string, it returns TRUE, otherwise it returns FALSE. Note that floating point type returns 1, which is TRUE.
if(is_numeric($k)){ $keys[]=$k; }
This will get an array containing numerical subscripts
Step 3: Use the min() function to obtain the minimum value in the numerical subscript array
min() function returns the minimum value in an array, or the minimum value among several specified values.
$min=min($keys);
Implementation sample code:
<?php header('content-type:text/html;charset=utf-8'); function f($arr) { foreach ($arr as $k => $v) { if (is_numeric($k)) { $keys[] = $k; } } var_dump($keys); $min = min($keys); echo "最小的数字下标:".$min; } $arr = array(5 => "5", "a" => "a", 2 => "2", "-1" => -1, "2", "0" => 0, "c" => "blue"); f($arr); $arr = array(5 => "5", 2 => "2", "2", "0" => 0,); f($arr); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to find the smallest number subscript in an array in php. For more information, please follow other related articles on the PHP Chinese website!