Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have got a strange problem about in_array recently which I cannot understand. e.g.

$a = array('a','b','c');
$b = array(1,2,3);

if (in_array(0,$a))
{
    echo "a bingo!
";
}
else
{
    echo "a miss!
";
}

if (in_array(0,$b))
{
    echo "b bingo!
";
}
else
{
    echo "b miss!
";
}

I ran it on my lamp,and got

a bingo!
b miss!

I read the manual and set the third parameter $strict as true,then it worked as expected.But does that mean I always need to set the strict parameter as true when using in_array?Suggestions would be appreciated.

Regards

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

It means you have to set the third parameter to true when you want the comparison to not only compare values, but also types.

Else, there is type conversions, while doing the comparisons -- see String conversion to numbers, for instance.

As a matter of fact, in_array without and with strict is just the same difference as you'll have between == and === -- see Comparison Operators.


This conversion, most of the time, works OK... But not in the case you're trying to compare 0 with a string that starts with a letter : the string gets converted to a numeric, which has 0 as value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...