In Laravel 11.x, the `Arr::isAssoc()` method is a convenient utility provided by the `Illuminate\Support\Arr` class. It is used to determine whether a given array is associative or indexed. An associative array is one where the keys are not purely sequential integers starting from 0 (e.g., `[‘name’ => ‘John’, ‘age’ => 25]`), while an indexed array has sequential integer keys (e.g., `[0 => ‘apple’, 1 => ‘banana’]`).
How `Arr::isAssoc()` Works?
-> Returns `true` if the array is associative.
-> Returns `false` if the array is indexed.
Example Usage:
<?php use Illuminate\Support\Arr; // Example 1: Associative array $assocArray = ['name' => 'John', 'age' => 25]; $isAssoc = Arr::isAssoc($assocArray); // true // Example 2: Indexed array $indexedArray = ['apple', 'banana', 'cherry']; $isAssoc = Arr::isAssoc($indexedArray); // false // Example 3: Mixed array (treated as associative) $mixedArray = [0 => 'apple', 2 => 'banana', 3 => 'cherry']; $isAssoc = Arr::isAssoc($mixedArray); // true ?>
Explanation:
1. Associative Array: The keys are strings or non-sequential integers.
Example: `[‘name’ => ‘John’, ‘age’ => 25]` → `Arr::isAssoc()` returns `true`.
2. Indexed Array: The keys are sequential integers starting from 0.
Example: `[0 => ‘apple’, 1 => ‘banana’]` → `Arr::isAssoc()` returns `false`.
3. Mixed Array: If the array has non-sequential or missing keys, it is treated as associative.
Example: `[0 => ‘apple’, 2 => ‘banana’]` → `Arr::isAss