5

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?

0

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Why they aren't of the same type when it is single element array ?
@JinuJD - I've updated my answer with a more clear description of what's going on

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.