Home > Backend Development > PHP Problem > PHP determines whether an array is a numeric array

PHP determines whether an array is a numeric array

(*-*)浩
Release: 2023-02-24 15:18:01
Original
4690 people have browsed it

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;
    }
Copy after login

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);
}
Copy after login

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
Copy after login

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!

Related labels:
php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template