Ethan H
Ethan H

Reputation: 625

PHP in_array() always returning false

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.

Upvotes: 7

Views: 5015

Answers (4)

Bart Friederichs
Bart Friederichs

Reputation: 33511

As already stated, Windows uses \r\n as end of line characters. Unix uses \n and Mac uses \r. To make portable code, use the PHP_EOL constant to explode your string:

$list_arr = explode(PHP_EOL, $list)

That way, you are sure it always works correctly.

Upvotes: 1

Mike Brant
Mike Brant

Reputation: 71384

That is a pretty odd way of getting values into a list. So I am assuming that you are ultimately trying to lines from a separate file into an array. In which case you would just do

file('path/to/file');

To read each line into a separate array item.

Where the file referenced looks like:

test
list
example

If you know the values up front like in your code sample, you should just put them into an array rather than reading them from a string.

If you simply must read the values from a string, I would suggest using PHP_EOL constant to define your line breaks. Like this:

$list = 'test' . PHP_EOL . 'list' . PHP_EOL . 'example';
$list_arr = explode(PHP_EOL, $list);

The PHP_EOL constant is going to give you a much better platform-independent way of getting values defining your line breaks.

Upvotes: 1

Mathieu Dumoulin
Mathieu Dumoulin

Reputation: 12244

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.

Upvotes: 11

gen_Eric
gen_Eric

Reputation: 227220

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

$list_arr = explode("\r\n",$list);

Upvotes: 8

Related Questions