PHP
Check if an Array is Associative or Sequential
Determine whether a given PHP array is associative (string keys, or non-sequential numeric keys) or a simple numerically indexed (sequential) array.
<?php
function is_associative(array $arr): bool
{
if (empty($arr)) {
return false; // An empty array is neither purely associative nor purely sequential.
}
return array_keys($arr) !== range(0, count($arr) - 1);
}
$indexedArray = ['apple', 'banana', 'cherry'];
$associativeArray = ['fruit' => 'apple', 'color' => 'red'];
$mixedArray = [0 => 'first', 2 => 'third']; // Sequential with missing keys
$emptyArray = [];
echo 'Indexed Array: ' . (is_associative($indexedArray) ? 'Associative' : 'Sequential') . "
";
echo 'Associative Array: ' . (is_associative($associativeArray) ? 'Associative' : 'Sequential') . "
";
echo 'Mixed Array: ' . (is_associative($mixedArray) ? 'Associative' : 'Sequential') . "
";
echo 'Empty Array: ' . (is_associative($emptyArray) ? 'Associative' : 'Sequential') . "
";
How it works: This code provides a utility function `is_associative()` to determine if a PHP array is associative or sequentially indexed. It works by comparing the array's keys with a perfect sequence of numbers from 0 to `count($arr) - 1`. If they don't match exactly, or if any keys are strings, the array is considered associative. This is useful for conditional logic based on array structure.