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 inconsistent. Native implementation provides:
None This adds a new function only.
PHP 8.6
There may be conflicts if userland code already defines is_assoc_array(). Such functions can be replaced with the built-in implementation.
No impact to SAPIs or OPcache.
Pick a title that reflects the concrete choice people will vote on.
Please consult the php/policies repository for the current voting guidelines.
Primary Vote requiring a 2/3 majority to accept the RFC:
Links to proof of concept PR.
If there is no patch, make it clear who will create a patch, or whether a volunteer to help with implementation is needed.
After the RFC is implemented, this section should contain:
Links to external references, discussions, or RFCs.
Keep this updated with features that were discussed on the mail lists.
If there are major changes to the initial proposal, please include a short summary with a date or a link to the mailing list announcement here, as not everyone has access to the wikis' version history.