Jump to content

problem with foreach


oha055

Recommended Posts

Hi!

I have a problem when echoing some lines of an exploded string. The output of the code is:

 

* [EMPRY LINE]

* line with some writing #1

* line with some writing #2

* line with some writing #3

etc.

 

I don't get why the first (empty) line is included..

 

<?php
$lines = explode('-', $text);
foreach($lines as $line) {
    echo '*', $line, "<br />";
} ?>

 

any help is appreciated! :)

Link to comment
https://forums.phpfreaks.com/topic/249568-problem-with-foreach/
Share on other sites

The $text starts with a hyphen. Before the hyphen is nothing, after the hyphen is the "first" line.

 

- If you know the $text always starts with a hyphen, you can trim it off, or remove the first item from $lines, or one of a billion other things.

- If you want to ignore all empty lines, filter them out.

Probably because the string starts with a "-", so the explode() splits the string on that first character and assigns an empty string to the first index. If you want to skip ANY empty values you can do this

foreach($lines as $line)
{
    if(!empty($line) { echo "* {$line}<br />\n"; }
}

 

Or if you want to skip lines that are empty OR only have white-space (i.e. spaces, tabs)

foreach($lines as $line)
{
    $line = trim($line);
    if(!empty($line) { echo "* {$line}<br />\n"; }
}

 

Lastly if you only want to skip the first index, but still output all other elements even if they are blank

array_shift($lines); //remove first element
foreach($lines as $line)
{
    echo "* {$line}<br />\n";
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.