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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With