Home >Backend Development >PHP Problem >PHP determines whether an array is a numeric array
PHP determines that the array is a numerical array
Specific idea: Get all the keys of the array: "array_keys()"
Traverse all keys to determine whether each key starts from 0 and increases by one in order.
The specific method is as follows: (Recommended learning: PHP programming from entry to proficiency)
function _checkAssocArray($arr) { $index = 0; foreach (array_keys($arr) as $key) { if ($index++ != $key) return false; } return true; }
The logic is very simple, associative array The keys will not all increase in the order: 0,1,2,3..., if it does, then there is no difference from the numerical array, just treat it the same way.
function is_assoc($arr) { return array_keys($arr) !== range(0, count($arr) - 1); }
Test
$arr = array(1, 2, 3, 4, 5, 6, 7); print is_assoc($arr); // 输出false $arr = array("foo" => "bar", "bar" => "foo"); print is_assoc($arr); // 输出true $arr = array("foo" => "bar", 3, 4, 5); print is_assoc($arr); // 输出true
The above is the detailed content of PHP determines whether an array is a numeric array. For more information, please follow other related articles on the PHP Chinese website!