PHP
Check if PHP Array is Associative
Implement a utility function to determine if a PHP array is associative (string keys) or sequentially indexed (numeric, starting from zero).
<?php
function is_associative_array(array $array): bool {
if ([] === $array) {
return false; // An empty array is considered sequential or neither
}
// Check if array keys are sequential starting from 0
return array_keys($array) !== range(0, count($array) - 1);
}
// Test cases
$sequential_array = [1, 2, 3, 'hello'];
$associative_array = ['a' => 1, 'b' => 2, 'c' => 3];
$mixed_array = [0 => 'a', 'test' => 'b', 1 => 'c']; // Behaves as associative for this check
$sparse_array = [0 => 'a', 2 => 'b']; // Behaves as associative due to non-sequential keys
$empty_array = [];
// var_dump(is_associative_array($sequential_array)); // Expected: bool(false)
// var_dump(is_associative_array($associative_array)); // Expected: bool(true)
// var_dump(is_associative_array($mixed_array)); // Expected: bool(true)
// var_dump(is_associative_array($sparse_array)); // Expected: bool(true)
// var_dump(is_associative_array($empty_array)); // Expected: bool(false)
?>
How it works: The `is_associative_array` function determines whether a given PHP array is associative (uses string keys or non-sequential numeric keys) or sequentially indexed (numeric keys starting from zero). It works by comparing the array's actual keys with a generated range of sequential numbers. If they don't match, or if the array is empty (which is generally treated as non-associative), it's considered associative. This is a crucial utility for handling dynamic array inputs, especially when dealing with data from JSON APIs or forms, where the structure might not always be predictable.