Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing array of keys of associative array to integer indexed array

I have written the following code to check whether an 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 doesn't return true for associative arrays with single element like:

array("a" =>9);

Why does it returns false for associative arrays with single element?

like image 325
Jinu Joseph Daniel Avatar asked Jul 05 '12 19:07

Jinu Joseph Daniel


1 Answers

You need to use !== in your comparison:

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

This generates the correct output of both of them being true.

Otherwise type juggling will consider the values for the single element array as equal:

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

Here, "a" == 0 is true (as "a" is silently cast to 0), but "a" === 0 is false.

like image 52
nickb Avatar answered Nov 07 '22 16:11

nickb