I have a while loop use to write a list. i'd like every element separated with a comma, but write a dot after the last one, not a coma. Here is my code
$exec = mysql_query($req);
while ($row = mysql_fetch_assoc($exec)){
echo '<strong>'.$row['name'].'</strong>, ';
}
开发者_如何学JAVA
But I don't know how to do that. I tried using count() or end(), but none of these works. A little help would be great !
$html = array();
$exec = mysql_query($req);
while ($row = mysql_fetch_assoc($exec)){
$html[] = '<strong>' . htmlspecialchars($row['name']) . '</strong>';
// --------------------^^^^^^^^^^^^^^^^! (1)
}
$html = implode(', ', $html) . '.';
(1) - Never output data to HTML without escaping it properly.
I like the use the implode function for this :)
$list = array();
$exec = mysql_query($req);
while ($row = mysql_fetch_assoc($exec)){
$list[] = '<strong>'.$row['name'].'</strong>';
}
$string = implode(", " , $list);
echo $string . ".";
HTH
Try this:
$exec = mysql_query($req);
$output = array();
while ($row = mysql_fetch_assoc($exec)){
$output[] = '<strong>'.$row['name'].'</strong>';
}
echo implode(',', $output), '.';
Build the string but don't output. Then, trim off the command and add a fullstop:
$exec = mysql_query($req);
$output = "";
while ($row = mysql_fetch_assoc($exec))
{
$output .= '<strong>'.htmlentities($row['name']).'</strong>, ';
}
if($output) echo rtrim($output, ', ').".";
精彩评论