Extra list item in a PHP foreach loop
Working on a basic "form to text file" evite list type of thing. Everything on it works great except that it's inserting an empty <li></li>
at the bottom of the list. I'm using开发者_开发问答 a carriage return delimiter and have tried using str_replace to remove the carriage return from the loop. But it's not quite working. Is there something I'm missing on this? Or any suggestions how to remove that bugger.
Here's the form processor file
$name = $_POST[ 'name' ];
$guests = $_POST[ 'guests' ];
$data = "$name $guests\r";
$open = fopen("list.txt", "a");
fwrite($open, $data);
fclose($open);
PHP Output File
$file = "list.txt";
$open = fopen($file, 'r');
$data = fread($open, filesize($file));
fclose($open);
$list = explode("\r", $data);
$string = str_replace("\r", "", $list);
foreach($string as $value) {
echo '<li>'.ucwords($value).'</li>'."\n";
}
And here is how the markup looks from the PHP output
<li>Person One 1</li>
<li>Person Two 4</li>
<li>Person Three 2</li>
<li></li>
Any help would be greatly appreciated.
Here's one way to code defensively for empty values...
foreach($string as $value)
{
//to be really foolproof, let's trim!
$value=trim($value);
//only output if we have something...
if (!empty($value))
{
echo '<li>'.ucwords($value).'</li>'."\n";
}
}
Use Trim to trim trailing enters of your string before exploding it
$list = explode("\r", trim($data));
Remove the str_replace
call, and just skip the elements that contain nothing, or only whitespace characters:
foreach($string as $value) {
if (!preg_match("/^\\s*$/", $value)) {
echo '<li>'.ucwords($value).'</li>'."\n";
}
}
精彩评论