I'm struggling with a behaviour in PHP and finally needed to sign up on stackoverflow as I could not find any answer to my problem for the very first time! :D
In my code, I'm getting the following content from a textarea (multiple lines):
10001;11;;;1;3;
10002;11;;;1;3;
10003;11;;;1;3;
I'm first exploding the several lines with explode("\n", $string);.
Second, I explode the elements of each line: explode(";", $string[0]);
The content of key 6 is empty, but PHP only recognizes the last element of the last line as empty:
Exploding the lines with
explode("\n", $string);
Array ( [0] => 10001;11;;;1;3; [1] => 10002;11;;;1;3; [2] => 10003;11;;;1;3; )
Exploding first line with
explode(";", $string[0]);
Array ( [0] => 10001 [1] => 11 [2] => [3] => [4] => 1 [5] => 3 [6] => )
Is last element of first line empty?
( if(empty($line1[6]) )
No.
Exploding second line with
explode(";", $string[1]);
Array ( [0] => 10002 [1] => 11 [2] => [3] => [4] => 1 [5] => 3 [6] => )
Is last element of second line empty?
( if(empty($line2[6]) )
No.
Exploding third line with
explode(";", $string[2]);
Array ( [0] => 10003 [1] => 11 [2] => [3] => [4] => 1 [5] => 3 [6] => )
Is last element of third line empty?
( if(empty($line3[6]) )
Yes
Can anyone tell me, why PHP always says that only the last element of the last line is empty, although every last element is?
Thank you very much in advance!
\r\n, not\n. You can usePHP_EOLinstead of"\n"for your initial explode. You can see what the lines do contain if they aren't empty, withvar_dump($line1[6]);\n: sandbox.onlinephpfunctions.com/code/…. But, reproducible if, as anyber suggests, the line ends are in fact\r\n: sandbox.onlinephpfunctions.com/code/…array_map('trim', explode("\n", $string))