I have a list of tags that I'm using to filter projects inside a data attribute.
I used split() for my array, however I need to add a comma as a separator if there is more than one item in the list. Ideally this is how I would like it to work.
// Senario 1 – Single item
<a href="#" data-tag="projects">Project Title</a>
// Senario 2 – More than 1 item
<a href="#" data-tag="product,commercial,housing">Project Title</a>
My current code:
<?php foreach($project->tags()->split(',') as $tag): ?>
<a href="#" data-tag="<?php echo $tag; ?>">Project</a>
<?php endforeach; ?>
I'm just not sure how to check if I've completed the loop after first.
Thanks for the help.
Try implode
function. manual
<a href="#" data-tag="<?php echo implode(',', $project->tags()) ?>">Project</a>
Build your string first before adding it into your anchor:
<?php
$result = '';
foreach($project->tags()->split(',') as $tag) {
$result .= sprintf('%s,', $tag);
}
//Will remove the last character of the string.
$result = substr($result, 0, -1);
?>
<a href="#" data-tag="<?php echo $result; ?>">Project</a>';