PHP
Determine if a PHP Array is Associative or Indexed
Write a utility function to reliably check whether a given PHP array is an associative array (string keys) or a sequentially indexed array (numeric, zero-based, continuous keys).
<?php
function isAssociative(array $array): bool {
if (empty($array)) {
return false; // An empty array is considered non-associative/indexed
}
// If keys are not 0, 1, 2, ..., then it's associative
return array_keys($array) !== range(0, count($array) - 1);
}
$indexedArray = [10, 20, 30];
$associativeArray = ['a' => 1, 'b' => 2];
$mixedArray = [0 => 'hello', 'key' => 'world']; // Treated as associative due to non-numeric key
$nonZeroStartIndex = [1 => 'first', 2 => 'second']; // Treated as associative due to non-sequential keys (or non-zero start)
$emptyArray = [];
echo 'indexedArray is associative? ' . (isAssociative($indexedArray) ? 'Yes' : 'No') . "
";
echo 'associativeArray is associative? ' . (isAssociative($associativeArray) ? 'Yes' : 'No') . "
";
echo 'mixedArray is associative? ' . (isAssociative($mixedArray) ? 'Yes' : 'No') . "
";
echo 'nonZeroStartIndex is associative? ' . (isAssociative($nonZeroStartIndex) ? 'Yes' : 'No') . "
";
echo 'emptyArray is associative? ' . (isAssociative($emptyArray) ? 'Yes' : 'No') . "
";
?>
How it works: This snippet provides a function `isAssociative` to determine if a PHP array is associative (has non-integer keys, or integer keys that are not sequential starting from zero). It works by comparing the array's actual keys (obtained via `array_keys`) with a perfect sequence of zero-based integers (generated via `range`). If they don't match, the array is considered associative. An empty array is typically considered non-associative/indexed for simplicity. This is useful when you need to handle array structures differently based on whether they use sequential numeric keys or arbitrary string/numeric keys.