PHP
Check if a PHP Array is Associative or Sequential
Understand how to programmatically determine if a PHP array is sequentially indexed (0, 1, 2...) or if it contains non-numeric or non-contiguous integer keys, classifying it as associative.
<?php
function isAssociative(array $array): bool
{
if (empty($array)) {
return false; // An empty array is neither strictly associative nor sequential
}
// If keys are not 0, 1, 2...count-1 then it's associative
return array_keys($array) !== range(0, count($array) - 1);
}
$sequentialArray = ['apple', 'banana', 'cherry'];
$associativeArray = ['fruit' => 'apple', 'color' => 'red'];
$mixedArray = [0 => 'first', 'one' => 'second']; // Technically associative
$nonContiguousSequential = [0 => 'a', 2 => 'c', 1 => 'b']; // Keys are 0, 2, 1, not 0, 1, 2
// var_dump(isAssociative($sequentialArray)); // Expected: false
// var_dump(isAssociative($associativeArray)); // Expected: true
// var_dump(isAssociative($mixedArray)); // Expected: true
// var_dump(isAssociative($nonContiguousSequential)); // Expected: true
// var_dump(isAssociative([])); // Expected: false
?>
How it works: The `isAssociative` function determines if a given PHP array is associative or sequential. It works by comparing the array's keys (obtained with `array_keys`) to a perfect sequential range of integers starting from 0 (generated with `range`). If the keys do not match this perfect sequence, the array is considered associative. An empty array is treated as neither.