Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A problem about in_array

Tags:

arrays

php

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

like image 627
Young Avatar asked Mar 19 '10 11:03

Young


People also ask

Is in_array case sensitive?

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.

Is in_array slow?

PHP's in_array() function is really slow.

What is the use of in_array ()?

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.

Does in_array work for associative array?

in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.


1 Answers

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.

like image 146
Pascal MARTIN Avatar answered Sep 22 '22 00:09

Pascal MARTIN