PHP arrays can behave as both lists and associative maps. Currently, PHP has no built-in function to detect whether an array is associative.
Userland frameworks implement helper functions for this purpose. Adding a native function improves performance, readability, and consistency.
<?php $data = ['a'=> 1, 'b' => 2]; var_dump(is_assoc_array($data)); // bool(true) ?>
Add a new core function:
<?php function is_assoc_array(array $array): bool {} ?>
This function determines whether an array is associative based on PHP’s internal array storage.
An array is considered associative when it is not a packed array internally.
<?php var_dump(is_assoc_array(['a' => 'a', 0 => 'b'])); // true var_dump(is_assoc_array([1 => 'a', 0 => 'b'])); // true var_dump(is_assoc_array([1 => 'a', 2 => 'b'])); // true var_dump(is_assoc_array([0 => 'a', 1 => 'b'])); // false var_dump(is_assoc_array(['a', 'b'])); // false var_dump(is_assoc_array([])); // false (empty array not associative) var_dump(is_assoc_array([1, 2, 3])); // false var_dump(is_assoc_array(['foo', 2, 3])); // false var_dump(is_assoc_array([0 => 'foo', 'bar'])); // true var_dump(is_assoc_array([1 => 'foo', 'bar'])); // true var_dump(is_assoc_array([0 => 'foo', 'bar' => 'baz'])); // true var_dump(is_assoc_array([0 => 'foo', 2 => 'bar'])); // true var_dump(is_assoc_array(['foo' => 'bar', 'baz' => 'qux'])); // true ?>
Userland solutions are slower and less consistent. Native implementation provides:
None This adds a new function only.
PHP 8.6
This function has been added to the ext-standard extension, which also contains is_assoc_array().
Primary Vote requiring a 2/3 majority to accept the RFC:
None
After the RFC is implemented, this section should contain:
Current discussion: https://news-web.php.net/php.internals/130115
None
1.0: Initial version under discussion