Fernando Anael Cabral Fernando Anael Cabral - 5 months ago 10
PHP Question

Problems with Empty Strings. Empty() not working

I'm building a form that'll create a Word doc. There's a part where the user will create a list, and will separete the list lines by using the " | " (vertical bar) as a delimeter. I'm trying to explode() a string like this: "First line| Second line| Third and last line |". As you guys saw, I placed a vertival bar delimiter after the last line, that's 'cause the user will probably do this mistake, and it will generate a empty line on the list.
I'm trying to avoid this error by using something like this:

$lines = explode("|",$lines);
for($a=0;$a<count($lines);$a++)
{
if(!empty($lines[$a]) or !ctype_space($lines[$a]))
{
//generate the line inside de Word Doc
}
}


This code works when I create the string by my own while testing the code, but won't work when the string come from a Form. And keep generating a empty line list inside the Word Doc.
When I var_dump() the $lines array it shows the last key as: [2]=> string(0) ""

I'm using Laravel and the form was created with the Form:: facade.(don't know if this matter, prob not)

If you guys could help me, I'd apreciate.

Answer

You may want to use PHP's && (and) rather than or.
For reference, see Logical Operators.

You only want to output the line if both empty() and ctype_space() return false. With your current code, blank strings will pass your if test because ctype_space() will return false even though empty() does not.

Strings made up entirely of spaces will also pass because empty() will return false even though ctype_space() returns true.

I suggest trimming white space from the string before checking empty():

$lines = explode("|",$lines);

if (!empty($lines)) {
  foreach ($lines as $line) {
    if (!empty(trim($line)) {
      // output this line
    }
  }
}

Also, see 'AND' vs '&&' as operator.