Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php, in_array, 0 value

Tags:

arrays

php

I was trying to understand the in_array behavior at the next scenario:

$arr = array(2 => 'Bye', 52, 77, 3 => 'Hey'); var_dump(in_array(0, $arr)); 

The returned value of the in_array() is boolean true. As you can see there is no value equal to 0, so if can some one please help me understand why does the function return true?

like image 336
Aviel Fedida Avatar asked Dec 12 '12 19:12

Aviel Fedida


People also ask

What does in_array return in PHP?

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.

How do you check if value exists in array of objects PHP?

The function in_array() returns true if an item exists in an array. You can also use the function array_search() to get the key of a specific item in an array. In PHP 5.5 and later you can use array_column() in conjunction with array_search() .

How do I view an array in PHP?

To display array structure and values in PHP, we can use two functions. We can use var_dump() or print_r() to display the values of an array in human-readable format or to see the output value of the program array.


1 Answers

This is a known issue, per the comments in the documentation. Consider the following examples:

in_array(0, array(42));      // FALSE in_array(0, array('42'));    // FALSE in_array(0, array('Foo'));   // TRUE 

To avoid this, provide the third paramter, true, placing the comparison in strict mode which will not only compare values, but types as well:

var_dump(in_array(0, $arr, true)); 

Other work-arounds exist that don't necessitate every check being placed in strict-mode:

in_array($value, $my_array, empty($value) && $value !== '0'); 

But Why?

The reason behind all of this is likely string-to-number conversions. If we attempt to get a number from "Bye", we are given 0, which is the value we're asking to look-up.

echo intval("Bye"); // 0 

To confirm this, we can use array_search to find the key that is associated with the matching value:

$arr = array(2 => 'Bye', 52, 77, 3 => 'Hey'); echo array_search(0, $arr); 

In this, the returned key is 2, meaning 0 is being found in the conversion of Bye to an integer.

like image 64
Sampson Avatar answered Sep 28 '22 07:09

Sampson