PHP
Check if PHP Array is Associative or Sequential
Determine whether a given PHP array uses sequential numeric keys (0, 1, 2...) or associative string/non-sequential integer keys with a simple utility function.
function isAssociative(array $array): bool {
if (empty($array)) {
return false; // An empty array is considered sequential (or neither)
}
return array_keys($array) !== range(0, count($array) - 1);
}
$sequentialArray = ['apple', 'banana', 'cherry'];
$associativeArray = ['fruit1' => 'apple', 'fruit2' => 'banana'];
$mixedArray = [0 => 'red', 2 => 'green', 3 => 'blue']; // Non-sequential keys
$emptyArray = [];
echo 'Sequential Array is associative: ' . (isAssociative($sequentialArray) ? 'Yes' : 'No') . "
";
// Expected output: Sequential Array is associative: No
echo 'Associative Array is associative: ' . (isAssociative($associativeArray) ? 'Yes' : 'No') . "
";
// Expected output: Associative Array is associative: Yes
echo 'Mixed (non-sequential) Array is associative: ' . (isAssociative($mixedArray) ? 'Yes' : 'No') . "
";
// Expected output: Mixed (non-sequential) Array is associative: Yes
echo 'Empty Array is associative: ' . (isAssociative($emptyArray) ? 'Yes' : 'No') . "
";
// Expected output: Empty Array is associative: No
How it works: The `isAssociative` function checks if an array's keys are strictly sequential, starting from 0. It does this by comparing the array's actual keys (`array_keys($array)`) to a generated range of sequential keys (`range(0, count($array) - 1)`). If they don't match exactly, the array is considered associative (or non-sequentially indexed). An empty array is conventionally considered non-associative for practical purposes.