← Back to all snippets
PHP

Determine if a PHP Array is Associative

Learn to differentiate between sequential (numerically indexed from 0) and associative arrays in PHP by checking if its keys are sequential and numeric.

<?php
function isAssociative(array $arr): bool {
    if (empty($arr)) {
        return false; // An empty array is typically considered sequential or non-associative
    }
    // If the array keys are not equivalent to a range starting from 0, it's associative
    return array_keys($arr) !== range(0, count($arr) - 1);
}

$sequentialArray = ['apple', 'banana', 'cherry'];
$associativeArray = ['a' => 'apple', 'b' => 'banana'];
$mixedKeysArray = [0 => 'apple', 'b' => 'banana'];
$nonZeroStartIndexedArray = [1 => 'apple', 2 => 'banana'];
$sparseIndexedArray = [0 => 'apple', 2 => 'cherry'];
$emptyArray = [];

echo "Sequential Array: " . (isAssociative($sequentialArray) ? 'Associative' : 'Sequential') . "
";
echo "Associative Array: " . (isAssociative($associativeArray) ? 'Associative' : 'Sequential') . "
";
echo "Mixed Keys Array: " . (isAssociative($mixedKeysArray) ? 'Associative' : 'Sequential') . "
";
echo "Non-Zero Start Indexed Array: " . (isAssociative($nonZeroStartIndexedArray) ? 'Associative' : 'Sequential') . "
";
echo "Sparse Indexed Array: " . (isAssociative($sparseIndexedArray) ? 'Associative' : 'Sequential') . "
";
echo "Empty Array: " . (isAssociative($emptyArray) ? 'Associative' : 'Sequential') . "
";
?>
How it works: This `isAssociative` function checks if an array's keys are perfectly sequential integers starting from 0. If `array_keys($arr)` does not match `range(0, count($arr) - 1)`, it implies either string keys, non-zero starting integer keys, or sparse integer keys, classifying the array as associative. This is useful for dynamically adapting code based on array structure.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs