PHP in_array () always returns false

PHP always returns false when I use in_array (), and regardless of whether or not it is in the array, it does not matter. For instance:

$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", although "test" is the 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 be

Why does it return false when it should be true? Please give any suggestions. The list that I actually use has more than 10 thousand values, so I just shortened it here.

+6
source share
4 answers

If you use this exact example and code on a Windows PC, the problem arises because Windows saves the line channels using:

 \r\n 

That way, when you split into \ n, you save the invisible \ r at the end of your elements, and for that reason they don't match.

+9
source

Your list is actually split \r\n , not just \n .

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

This is a rather strange way to get values ​​in a list. Therefore, I assume that you are ultimately trying to output from a separate file to an array. In this case, you just do

 file('path/to/file'); 

To read each line into a separate element of the array.

If the file link looks like this:

 test list example 

If you know the values ​​in front of the front, as in your code example, you should just put them in an array and not read them from a string.

If you just have to read values ​​from a string, I would suggest using the PHP_EOL constant to define line breaks. Like this:

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

The PHP_EOL constant will give you a much better platform-independent way of getting values ​​that define your line breaks.

+1
source

As already mentioned, 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 blow your line:

 $list_arr = explode(PHP_EOL, $list) 

Thus, you are sure that it always works correctly.

0
source

Source: https://habr.com/ru/post/920629/


All Articles