Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

arrays - PHP in_array() / array_search() odd behaviour

I have found some odd behaviour while I was using the PHP function in_array(). I have an array like this:

$arr = [TRUE, "some string", "something else"];

Now if I want to check if "test" is in the array it is clearly not, but in_array() still returns TRUE, why is that?

$result = in_array("test", $arr);
var_dump($result);  //Output: bool(true)

The same thing happens when using array_search():

$result = array_search("test", $arr);
var_dump($result);  //Output: int(0)

I thought maybe that the value TRUE in the array was automatically causing the function to return TRUE for every result without checking the rest of the array, but I couldn't find any documentation that would suggest that very odd functionality.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This behaviour of the function in_array() and array_search() is not a bug, but instead well documented behaviour.

Both functions have a 3rd optional parameter called $strict which by default is FALSE:

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )

Now what that means is that by default both functions use loosely(==) comparison to compare the values. So they only check if the values are the same after PHP type juggling and without checking the type. Because of that in your example TRUE == "any none emtpy string" evaluates to TRUE.

So by setting the 3rd parameter to TRUE while calling the function you say that PHP should use strict(===) comparison and it should check value AND type of the values while comparing.

See this as a reference: How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...