Home > Article > Backend Development > How to determine whether an array is an index array in php
Judgment steps: 1. Use array_keys() to get all the key names of the original array, the syntax is "array_keys(array)"; 2. Use array_filter() to filter the array, the syntax is "function f($v){return (is_string($v));}$res=array_filter($keys,"f");" will return a filter array containing string elements; 3. Determine whether the filter array is an empty array, and if it is empty, the array is an index array.
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
In php, the subscript of the index array ( Key name) consists of numbers. If a key name in an array is not a number, then the array is an associative array (not an index array).
So you only need to determine whether the key names of the array are all numbers to determine whether an array is an index array.
Implementation steps:
Step 1: Use the array_keys() function to obtain all the key names of the original array
array_keys( ) function returns a new array containing all the keys in the array.
array_keys(array,value,strict)
Parameters | Description |
---|---|
array | Required . Specifies an array. |
value | Optional. You can specify a key value, and then only the key name corresponding to that key value will be returned. |
strict | Optional. Used with the value parameter. Possible values:
|
<?php header('content-type:text/html;charset=utf-8'); $arr=array("r"=>"red",2,3,"hello",5,6); var_dump($arr); $keys=array_keys($arr); var_dump($keys); ?>
Step 2: Use array_filter() and is_string() functions to filter the array and return The string elements in the key name array
function f($v){ return(is_string($v)); } $res=array_filter($keys,"f"); var_dump($res);
will return a filtered array containing string elements
Step 3: Judgment Filter whether the array is an empty array
$res==[]
If it is empty, the array is an index array
If it is not empty, the array It is not an index array, it is an associative array
Implementation code:
<?php header('content-type:text/html;charset=utf-8'); function f($v){ return(is_string($v)); } function fun($arr){ $keys=array_keys($arr); $res=array_filter($keys,"f"); if($res==[]){ echo "数组是索引数组<br>"; }else{ echo "数组不是索引数组,是关联数组<br>"; } } $arr=array("r"=>"red",2,3,"hello",5,6); var_dump($arr); fun($arr); $arr=array(1,2,3,"hello",5,6); var_dump($arr); fun($arr); ?>
Recommended study: "PHP video tutorial》
The above is the detailed content of How to determine whether an array is an index array in php. For more information, please follow other related articles on the PHP Chinese website!