in_array PHP Function Bug July 27, 2007
Posted by ordinarywebguy in PHP, Programming.trackback
See the code:
<?php
$array1 = array(‘php’, ‘java’, ‘ruby’, ‘asp’);
$array2 = array(‘php’ => ‘PHP.net’, ‘java’ => ‘java.com’, 0 => ‘javascript’, 1 => ‘actionscript’);foreach ($array2 as $key => $value) {
if ( in_array($key, $array1) ) {
print “in array: $key <br />”;
} else {
print “not in array: $key <br />”;
} # end if} # end foreach
?>
Output:
in array: php
in array: java
in array: 0
not in array: 1
Expected Output:
in array: php
in array: java
not in array: 0
not in array: 1
Though the expected output above can be achieve via supplying TRUE to its third paramater which will set strict typing comparison between the value and array:
<?php
$array1 = array(‘php’, ‘java’, ‘ruby’, ‘asp’);
$array2 = array(‘php’ => ‘PHP.net’, ‘java’ => ‘java.com’, 0 => ‘javascript’, 1 => ‘actionscript’);foreach ($array2 as $key => $value) {
if ( in_array($key, $array1, TRUE) ) {
print “in array: $key <br />”;
} else {
print “not in array: $key <br />”;
} # end if} # end foreach
?>
How come that there’s a “0″ value on array $array1? That’s why I consider it a bug. I don’t know if someone has already experience this. I hope somebody could further explain this to me. I’ll also post this bug at PHP.net.
Note:
The script runs in PHP Version: 5.1.1

Reported: http://bugs.php.net/bug.php?id=42131
[...] August 3rd, 2007 Just a follow that I indeed deferred to my post: in_array PHP Function Bug. [...]
Hello , could you show me how to post PHP code onto wordpress blog , I could not get it appear like you do , How you can display code correctly ?
This is not a bug, it’s a gotcha.
Internally, the in_array() function does a $val1 == $val2 comparison. If one side of the == (doesn’t matter which side) is an int, the other will be converted to an int as well. The value of a string in int is 0.
See:
$t = “hello”;
var_dump((int)$t); // outputs int (0)
This is expected behaviour, although it had me stumped as well…
Try not to mix ints and strings as array keys.
When you add the third parameter (true) the comparison will be $val1 === $val2, and that’s why it works.
It’s debatable if a string’s int value is 0, but what else should it be?
Привет.
Продаю персональный сертификат WebMoney за $99.
Можете проверить: WMID 322973398779 Redfern
Всё чисто, не одной жалоб. Сделан на утерянные документы. Всё законно.
Если нужно, то есть сертификаты ещё.
Стучацо в личную почту на Вебмани.
Это не спам. Не пишите на мой WMID жалобы в арбитраж Вебмани.
This is a bug.
for example,
$arr = array(
['thing'] => ‘thing’
['other'] => 0
);
in_array(‘other’, $arr);
will return TRUE, even though other is not a VALUE, but is a KEY, which essentially means that the in_array function doesn’t work as advertised. This is why your function got the unexpected results.