Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in_array() always returns TRUE [duplicate]

Tags:

arrays

php

$arrValue = array('first', 'second');
$ret = in_array(0, $arrValue);
var_dump($ret);
var_dump($arrValue);

Above example gives following result:

bool(true)
array(2) {
  [0]=> string(5) "first"
  [1]=> string(6) "second"
}

Why in_array() matches needle 0 to any given haystack?

like image 210
Index Avatar asked May 19 '14 10:05

Index


People also ask

How many times does 1 appear in the input array?

Example 1: Input: nums = [1, 2, 3, 1] Output: true. Explanation: 1 appeared two times in the input array. Example 2: Input: nums = [1, 2, 3, 4] Output: false Explanation: input array does not contain any duplicate number. Disclaimer: Don’t jump directly to the solution, try it out yourself first.

How many duplicates are there in an array in O (n)?

Explanation: Duplicate element in the array are 1 , 3 and 6 Input: n = 6, array = {5, 3, 1, 3, 5, 5} Output: 3 and 5. Explanation: Duplicate element in the array are 3 and 6 Duplicates in an array in O (n) and by using O (1) extra space | Set-2 .

What is the input and output of the array N=7?

Input: n = 7 , array = {1, 2, 3, 1, 3, 6, 6} Output: 1, 3 and 6. Explanation: Duplicate element in the array are 1 , 3 and 6 Input: n = 6, array = {5, 3, 1, 3, 5, 5} Output: 3 and 5.

Do array elements have to be in limited range?

This solution doesn’t require array elements to be in limited range. Better Solution : Sort the input array and find the first element with exactly k count of appearances. Efficient Approach: Efficient approach is based on the fact that array has numbers in small range (1 to 1000).


1 Answers

That's because the function uses a non-strict comparison. The string in the array is compared to integer 0. Some typecasting is happening with data loss, and both are regarded the same:

var_dump(0 == 'first'); //  bool(true)

So solve this, you can use the third parameter and set it to true to request strict comparison.

$ret = in_array(0, $arrValue, true);

Keep in mind, through, that strict is really strict. In a strict comparison, 0 is not equal to "0".

Docs: http://nl3.php.net/in_array

like image 120
GolezTrol Avatar answered Nov 05 '22 07:11

GolezTrol