PHP中如何检查一个变量是否为关联数组? 发布时间:2023/10/11 在PHP中,可以使用`is_array()`函数来检查一个变量是否为数组。如果变量是一个关联数组,即它的键是字符串而不是整数,则可以使用`array_keys()`函数来获取数组的所有键,然后判断是否有字符串键存在。 下面是一个示例代码: <?php $assocArray = ['name' => 'John', 'age' => 25, 'city' => 'New York']; $indexedArray = [1, 2, 3, 4, 5]; if (is_array($assocArray)) { $keys = array_keys($assocArray); $isAssociative = false; foreach ($keys as $key) { if (!is_int($key)) { $isAssociative = true; break; } } if ($isAssociative) { echo "The variable is an associative array."; } else { echo "The variable is an indexed array."; } } else { echo "The variable is not an array."; } ?>复制代码 输出结果为: The variable is an associative array.复制代码