Link to home
Start Free TrialLog in
Avatar of badwolfff
badwolfffFlag for United Kingdom of Great Britain and Northern Ireland

asked on

How do I remove a trailing "comma" from my PHP for each function?

I have a working piece of PHP code which iterates a number of comma-separated values.
What I am having a difficult time doing is removing the trailing comma at the end of the last item found.

<?php foreach($vendor_cat as $vendorcat) { ?>
    <span id="vendor_category_list"><a href="<?php echo $vendorcat['href']; ?>" ><?php echo $vendorcat['category_name']; ?></a>,</span>
<?php } ?>

Open in new window


any help would be greatly apprecaited.

thanks in advance
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Your first problem is that ,</span> is not part of a PHP string but part of the HTML content which PHP doesn't even see.
Avatar of badwolfff

ASKER

Hi,

thanks. Could the function not be rewritten to count the number of items for that loop and add that many -1 commas?

I've done similar stuff in JavaScript but in PHP I am not sure how to do it.

thanks
PHP doesn't touch the HTML that is in between the PHP tags.  You have to put all of that in a PHP string for PHP to do anything with it.  If you do that then you can replace the final instance with a version that does not have the comma.
Ok
Could you help me with the code?
thanks
In the meantime I was able to get an iteration count inside the for each function using:
<?php echo count($vendor_cat); ?>
That doesn't help as long as the data is not in a PHP string.  This is untested but it is the basic idea.  You create the whole string in a PHP variable and then replace the last part.
<?php 
$thestring = '';
foreach($vendor_cat as $vendorcat) { 
	$thestring .= '<span id="vendor_category_list"><a href="'.$vendorcat['href'].'" >'.$vendorcat['category_name'].'</a>,</span>'
}
$thestring = substr_replace($thestring, '</span>', -8, 8) // http://php.net/manual/en/function.substr-replace.php
?>

Open in new window

In case you're new to PHP and want to learn the language, this article has some helpful links.
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html
Thanks Ray, trying to fix someone else's code. Mostly I can manage myself but sometimes there are these awkward problems.

Dave by the way after your function the out is empty now.
ASKER CERTIFIED SOLUTION
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial