$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?
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.
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 .
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.
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).
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
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