Comparing an array of keys of an associative array with an integer indexed array

I wrote the following code to check if the array is associative or not

function is_associative( $arr ) {
    $arr = array_keys( $arr );
    return $arr != array_keys( $arr );
}

It returns true for arrays like:

array("a" => 5,"b" => 9);

and false for numeric arrays

But it does not return true for associative arrays with one element like:

array("a" =>9);

Why does it return false for associative arrays with one element?

+5
source share
1 answer

You need to use !==for comparison:

return $arr !== array_keys( $arr );

This generates the correct conclusion , which is true.

Otherwise, type juggling will consider the values ​​for an array of single elements equal:

array(1) { [0]=> string(1) "a" } 
array(1) { [0]=> int(0) }

"a" == 0 ( "a" 0), "a" === 0 false.

+8

All Articles