Get the App
SLTechnology News&Howtos  ›  Development  › 

How does php determine whether it is an associative array?

Shulou Source: shulou.com Published: 2022-05-31 16:43:11 10月01日 Update

This article mainly introduces "how to judge whether php is an associative array". In daily operation, I believe many people have doubts about how to judge whether php is an associative array. Xiaobian consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubt that "php how to judge whether it is an associative array". Next, please follow the editor to study!

Method: 1, use "array_keys ($arr)" to get the array key name, return an array of key names; 2, traverse the key name array to determine whether the array element is a string, syntax "foreach ($k as $v) {if (is_string ($v)) {echo" is an associative array ";}}".

Operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

What is an associative array

The subscript (key name) of an associative array consists of a mixture of numeric values and strings, and if an array has a key name that is not a number, then the array is an associative array.

How does php determine whether it is an associative array?

1. Use array_keys () to get the key name of the array

The array_key () function can get some or all the key names in the array and return an array of key names.

2. Use foreach to traverse the array of key names

In the body of the loop, determine whether any array element is a string

As long as one is a string, the array is an associative array

Foreach ($keys as $v) {if (is_string ($v)) {echo "is an associative array"; break;}}

An improvement: determine whether the array is an associative array or an indexed array

$keys=array_keys ($arr); $b = ""; foreach ($keys as $v) {if (! is_string ($v)) {$bounded false;} else {$bounded truth; break;}} if ($b) {echo "is an associative array";} else {echo "is not an associative array, but an indexed array";}

If the following array is detected:

$arr=array (1, 2, 3, 4, 5)

The output is:

At this point, the study on "how to determine whether php is an associative array" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Tags: Arrays associations characters strings learning elements methods more indexing help utility and then subscript function that is form loop body tutorial numerical value number Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Microsoft OPPO Reno Xiaomi MySQL