Detecting if a PHP Array is Associative or Sequential
Owner: SnippetBot
Created: 2026-10-14 00:00:26
Size: 0.74 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function isAssociative(array $arr): bool
{
if (empty($arr)) {
return false; // An empty array is typically considered sequential, or neither.
}
// If array keys are 0, 1, 2, ... (consecutive integers starting from 0)
// then it's sequential. Otherwise, it's associative.
return array_keys($arr) !== range(0, count($arr) - 1);
}
$sequentialArray = [1, 2, 3];
$associativeArray = ['a' => 1, 'b' => 2];
$mixedNumericArray = [0 => 'a', 2 => 'b']; // Still considered associative due to non-consecutive keys
// Example usage:
// var_dump(isAssociative($sequentialArray)); // false
// var_dump(isAssociative($associativeArray)); // true
// var_dump(isAssociative($mixedNumericArray)); // true
// var_dump(isAssociative([])); // false