phparraysassociative-array

Differentiate an associative array from a regular array


Without having to change the function signature, I'd like a PHP function to behave differently if given an associative array instead of a regular array.

Note: You can assume arrays are homogenous. E.g., array(1,2,"foo" => "bar") is not accepted and can be ignored.

function my_func(Array $foo){
  if (…) {
    echo "Found associative array";
  }
  else {
    echo "Found regular array";
  }
}


my_func(array("foo" => "bar", "hello" => "world"));
# => "Found associative array"

my_func(array(1,2,3,4));
# => "Found regular array"

Is this possible with PHP?


Solution

  • Just check the type of any key:

    function is_associative(array $a) {
        return is_string(key($a));
    }
    
    $a = array(1 => 0);
    $a2 = array("a" => 0);
    
    var_dump(is_associative($a)); //false
    var_dump(is_associative($a2)); //true