rfc:is_assoc_array

PHP RFC: Add is_assoc_array

Introduction

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)
 
?>

Proposal

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.

Examples

<?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
 
?>

Why This is Needed

  • Developers frequently need to check the array type:
  • JSON encoding logic
  • API validation
  • Config parsing
  • Data normalization

Userland solutions are slower and less consistent. Native implementation provides:

  • O(1) performance
  • Standard behavior
  • Cleaner code

Backward Incompatible Changes

None This adds a new function only.

Proposed PHP Version(s)

PHP 8.6

RFC Impact

To Existing Extensions

This function has been added to the ext-standard extension, which also contains is_assoc_array().

Voting Choices

Primary Vote requiring a 2/3 majority to accept the RFC:

Add is_assoc_array()?
Real name
Final result:
This poll has been closed.

Patches and Tests

None

Implementation

After the RFC is implemented, this section should contain:

  1. the version(s) it was merged into
  2. a link to the git commit(s)
  3. a link to the PHP manual entry for the feature

References

Rejected Features

None

Changelog

1.0: Initial version under discussion

rfc/is_assoc_array.txt · Last modified: by arshidkv12