Reputation: 95
I used several different posts on this site to figure out how to remove the last comma in a string. Apparently it's a classic question, but what I can't figure out is why it's adding an extra white space before the comma and not after the comma as one would expect?
As always I've played around with the code but I can't figure out where the extra white space comes from, please help me I'm going blind!
<?php $comma = ""; ?><?php foreach ($tags as $tag) { ?>
<?php echo $comma; ?><a href="<?php echo $tag['href']; ?>">
<?php echo $tag['tag']; ?></a><?php $comma = ","; ?>
Upvotes: 0
Views: 295
Reputation: 6441
I would rather write the whole thing as such:
<?php
$tag_strings = array();
foreach ($tags as $tag)
{
$tag_strings[] = "<a href='" . $tag['href'] . "'>" . $tag['tag'] . "</a>";
}
echo implode(',', $tag_strings);
Upvotes: 2
Reputation: 13344
The blank space is due to the line break in your HTML after the <a>
element opens.
A better output soution would be:
<?php
$total = count( $tags);
$x = 0;
foreach ( $tags as $tag ){
$x++;
echo '<a href="' . $tag['href'] . '">' . $tag['tag'] . '</a>';
if ( $x < $total ) echo ',';
}
?>
Upvotes: 2
Reputation: 37701
Perhaps you have a white space in your HTML code between the PHP tags... Why don't you rewrite it to something like this:
<?php $comma = '';
foreach ($tags as $tag) {
echo "$comma<a href='{$tag['href']}'>{$tag['tag']}</a>";
$comma = ',';
} ?>
Upvotes: 2