oha055 Posted October 21, 2011 Share Posted October 21, 2011 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! Quote Link to comment Share on other sites More sharing options...
requinix Posted October 21, 2011 Share Posted October 21, 2011 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. Quote Link to comment Share on other sites More sharing options...
Psycho Posted October 21, 2011 Share Posted October 21, 2011 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"; } Quote Link to comment Share on other sites More sharing options...
oha055 Posted October 21, 2011 Author Share Posted October 21, 2011 Thanks to both of you! Much appreciated! I went for this solution: <?php $lines = explode('-', $text); array_shift($lines); foreach($lines as $line) { echo '*', $line, "<br />"; } ?> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.