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
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.

Link to comment
Share on other sites

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";
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.