in_array() always returns true if numbers are in the array

Viewed 30

This is code

<?php
$numbers = '3,5,1';
$exploded = array_filter(explode(',', $numbers));
$arr = [5, 6, 7, 8];

print_r($exploded);

foreach($arr as $num){
    echo "<br>---".$num.' --- is in array?  ';
    print_r(in_array($num, $arr));
}
?> 

The output

Array ( [0] => 3 [1] => 5 [2] => 1 )
---5 --- is in array? 1
---6 --- is in array? 1
---7 --- is in array? 1
---8 --- is in array? 1 

Why does it return always true even the number is not in the array?

1 Answers

The correct code

<?php
$numbers = '3,5,1';
$exploded = array_filter(explode(',', $numbers));
$arr = [5, 6, 7, 8];

print_r($exploded);

foreach($arr as $num){
    echo "<br>---".$num.' --- is in array?  ';
    print_r(in_array($num, $exploded));
}
?> 
Related