PHP

Determine if PHP Array is Associative

Learn to reliably check if a given PHP array is associative (uses string keys or non-sequential numeric keys) or a simple numerically indexed array.

<?php
function isAssociativeArray(array $array): bool {
    if (empty($array)) {
        return false; // An empty array is typically considered sequential for practical purposes
    }
    // Check if keys are consecutive integers starting from 0
    // This is the most common definition of a "sequential" array in PHP
    return array_keys($array) !== range(0, count($array) - 1);
}

// Test cases
$sequential = [1, 2, 3, 4]; // Keys: 0, 1, 2, 3
$sparseSequential = [0 => 1, 2 => 3, 4 => 5]; // Keys: 0, 2, 4 (not 0,1,2,3,4)
$associative = ['a' => 1, 'b' => 2]; // Keys: 'a', 'b'
$mixedKeys = [0 => 'apple', 'color' => 'red', 1 => 'banana']; // Keys: 0, 'color', 1
$emptyArray = [];

echo "isAssociativeArray([1, 2, 3, 4]): " . (isAssociativeArray([1, 2, 3, 4]) ? 'true' : 'false') . "
"; // Expected: false
echo "isAssociativeArray([0 => 1, 2 => 3, 4 => 5]): " . (isAssociativeArray([0 => 1, 2 => 3, 4 => 5]) ? 'true' : 'false') . "
"; // Expected: true
echo "isAssociativeArray(['a' => 1, 'b' => 2]): " . (isAssociativeArray(['a' => 1, 'b' => 2]) ? 'true' : 'false') . "
"; // Expected: true
echo "isAssociativeArray([0 => 'apple', 'color' => 'red', 1 => 'banana']): " . (isAssociativeArray([0 => 'apple', 'color' => 'red', 1 => 'banana']) ? 'true' : 'false') . "
"; // Expected: true
echo "isAssociativeArray([]): " . (isAssociativeArray([]) ? 'true' : 'false') . "
"; // Expected: false
How it works: This function determines if a PHP array is "associative" by checking if its keys are not a perfect sequential range starting from zero (e.g., 0, 1, 2...). If `array_keys()` does not return the same as `range(0, count($array) - 1)`, it implies either string keys, non-zero starting numeric keys, or gaps in numeric keys, classifying it as associative. An empty array is considered non-associative for practical purposes, fitting common programming needs.

Need help integrating this into your project?

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

Hire DigitalCodeLabs