Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP in_array() always returning false

Tags:

arrays

php

PHP is always returning false when I use in_array(), and whether it is or isn't in the array doesn't matter. For example:

$list = 'test
list
example';
$list_arr = array();
$list_arr = explode("\n",$list);
if (in_array('test',$list_arr)) {
    echo 'Found';
}
else {
    echo 'Not Found';
}

Returns 'Not Found' even though 'test' is a value in the array

$list = 'test
list
example';
$list_arr = array();
$list_arr = explode("\n",$list);
if (in_array('qwerty',$list_arr)) {
    echo 'Found';
}
else {
    echo 'Not Found';
}

Returns 'Not Found', as it should

Why is it returning false when it should be true? Please give any suggestions. The list I am actually using has more than 10K of values and therefore I just shortened it here.

like image 938
Ethan H Avatar asked Jul 16 '12 20:07

Ethan H


2 Answers

If you are using this exact example and are coding on a Windows PC, the problem comes from the fact that Windows stores line feeds using:

\r\n

Thus, when you split on \n only you keep an invisible \r at the end of your items and they don't match for that reason.

like image 142
Mathieu Dumoulin Avatar answered Sep 24 '22 09:09

Mathieu Dumoulin


Your list is actually separated by \r\n, not just \n.

$list_arr = explode("\r\n",$list);
like image 40
Rocket Hazmat Avatar answered Sep 24 '22 09:09

Rocket Hazmat