PHP
Determine if a PHP Array is Associative or Sequential
Write a utility function to reliably check whether a PHP array uses sequential numeric keys starting from zero or contains associative string keys.
<?php
/**
* Checks if an array is associative (has non-numeric or non-sequential keys).
* Returns true for associative, false for sequential/list-like.
*/
function is_associative_array(array $array): bool {
if (empty($array)) {
return false; // An empty array is considered sequential
}
// If array keys are not a range from 0 to count-1, it's associative.
// PHP 8.1+ offers array_is_list() for this, but this is for older versions.
return array_keys($array) !== range(0, count($array) - 1);
}
// Example arrays
$sequentialArray = [1, 2, 3];
$associativeArray = ['a' => 1, 'b' => 2];
$mixedArray = [0 => 'apple', 'color' => 'red']; // Keys are 0 and 'color'
$nonZeroStartSequential = [1 => 'first', 2 => 'second'];
$emptyArray = [];
echo 'Is sequentialArray associative? ' . (is_associative_array($sequentialArray) ? 'Yes' : 'No') . "
";
// Output: No
echo 'Is associativeArray associative? ' . (is_associative_array($associativeArray) ? 'Yes' : 'No') . "
";
// Output: Yes
echo 'Is mixedArray associative? ' . (is_associative_array($mixedArray) ? 'Yes' : 'No') . "
";
// Output: Yes
echo 'Is nonZeroStartSequential associative? ' . (is_associative_array($nonZeroStartSequential) ? 'Yes' : 'No') . "
";
// Output: Yes
echo 'Is emptyArray associative? ' . (is_associative_array($emptyArray) ? 'Yes' : 'No') . "
";
// Output: No
/* For PHP 8.1+ you can use array_is_list() which is more direct:
function is_associative_array_php81(array $array): bool {
return !array_is_list($array);
}
*/
?>
How it works: This snippet provides a function `is_associative_array` to determine if a given PHP array is associative or sequential (list-like). It works by comparing the array's actual keys (obtained with `array_keys`) to a numerically sequential range of keys from 0 up to `count($array) - 1`. If the key sets don't match, the array is considered associative. For PHP 8.1 and later, the built-in `array_is_list()` function offers a more direct and often more performant way to achieve the same check.