Skip to content
Advertisement

PHP: Exploding string => last element is empty, but not recognized as empty

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! 😀

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!

Advertisement

Answer

The browser is normalising the line separation with carriage return line feeds. So when you split on a line feed, you still have a carriage return in the last part.

<?php
$data = $_POST['data'];

$lines = explode("n", $data);
//$lines = preg_split('@R@', $data);

foreach($lines as $line) {
    $parts = explode(';', $line);
    var_dump(empty($parts[6]));
}
?>
<form method='POST'>
    <textarea name='data'>10001;11;;;1;3;
10002;11;;;1;3;
10003;11;;;1;3;</textarea>
    <input type='submit'>
</form>

Output (without the form code upon form submission):

bool(false)
bool(false)
bool(true)

Swap the explode line for the preg_split one above and the output is:

bool(true)
bool(true)
bool(true)

R escape sequence matches any Unicode newline sequence. (Please correct this definition if wrong.)

Note trailing space could be an issue. Be careful with user input.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement