Home >Backend Development >PHP Problem >How to determine whether it is an associative array or an index array in php
Judgment method: 1. Use array_values() to convert the specified array into an index array; 2. Use array_diff_key() to compare the key names of the original array and the index array, and return a difference array; 3. Use empty() ) determines whether the difference array is an empty array. If so, the original array is an index array, otherwise it is an associative array.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php determines whether it is related Array or index array method:
Implementation idea:
Use the array_values() function to obtain all key values of the specified array and convert them For the index array
Use the array_diff_key() function to compare the key names of the converted index array and the original array, and return the difference array
Use empty () Determine whether the difference array is an empty array. If the difference array is an empty array, the original array is an index array, otherwise it is an associative array.
Implementation code:
<?php header("Content-type:text/html;charset=utf-8"); function f($arr){ $value=array_values($arr); $result=array_diff_key($arr,$value); var_dump($result); if (empty($result)){ echo "原数组为索引数组"; } else{ echo "原数组为关联数组"; } } $arr1=array("a"=>"red","b"=>"green","c"=>"blue"); f($arr1); $arr2=array(1,2,3,4,5); f($arr2); ?>
Description:
array_values() function can Get the values of all elements in the array; this function is particularly suitable for arrays with confusing element subscripts, or for converting associative arrays into indexed arrays.
array_diff_key() function is used to compare the key names of two (or more) arrays and return the difference array.
If the difference array is an empty array, the key names of the two (or more) arrays are the same.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to determine whether it is an associative array or an index array in php. For more information, please follow other related articles on the PHP Chinese website!