开发者

A problem about in_array

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!\n";
}
else
{
    echo "a miss!\n";
}

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

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 wh开发者_StackOverflowen using in_array?Suggestions would be appreciated.

Regards


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.


The “default” mode of in_array is using a loose comparison like the == comparison operator does. That means 0 is compared like this:

var_dump(0 == 'a');  // bool(true)
var_dump(0 == 'b');  // bool(true)
var_dump(0 == 'c');  // bool(true)

Now the loose comparison operator == is using string conversion to integer before actually comparing the values:

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.

And 'a', 'b' and 'c' are all converted to 0:

var_dump((int) 'a');  // int(0)
var_dump((int) 'b');  // int(0)
var_dump((int) 'b');  // int(0)

But when using in_array in strict mode (set third parameter to true), a strict comparison (===) is done, that means both the value and type must be equal:

var_dump(0 === 'a');  // bool(false)
var_dump(0 === 'b');  // bool(false)
var_dump(0 === 'c');  // bool(false)

So when using the in_array in strict mode, you’re getting the expected result:

var_dump(in_array(0, $a, true));  // bool(false)


In your first example, every value of the array $a, when converted to numeric, is 0. That's why your first example results in "a bingo".

You don't have to use the strict parameter if you know you rely on implicit conversion, or that your datatypes are the same ( e.g. searching for a string in an array of string ). Otherwise you should use the strict parameter, the same you should use === instead of == when comparing two values that must be of the same type.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜