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 when using in_array
?Suggestions would be appreciated.
Regards
The in_array() function searches an array for a specific value. Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.
PHP's in_array() function is really slow.
The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.
in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.
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.
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