-1

I want want to show an album's artists separated by comma and as a link. Artist's names are saved in array. Code will explain more.

    <?php
    $Artist_Name = array("artist1", "artist2","artist3");
    ?>
    <p class="style18"><b>Artists</b>: <span class="style24">
    <?php
    foreach ($Artist_Name as $_value) {
    $Value_new = str_replace(' ', '-', $_value);
    ?>
    <a href= "<?=BASE_PATH?>artist/<?=$Value_new?>"><?=$_value?></a>, 

I'm getting the following result.

artist1, artist2, artist3,

I just want to kill that last comma and. Space. Thanks in advance. Any help would be great :)

Pradeep
  • 39
  • 9
  • 1
    Possible duplicate of [PHP - How to remove all specific characters at the end of a string?](http://stackoverflow.com/questions/2053830/php-how-to-remove-all-specific-characters-at-the-end-of-a-string) – Wouter Vanherck Apr 09 '17 at 08:14

3 Answers3

1

Use implode(', ', $Artist_Name) (see implode for details)

Update

For more complex cases an array_map can be used for per-element processing:

$Artist_Name = array("artist1", "artist2","artist3");
$artist_links = array_map(
    function($value) {
        return '<a href="/' . $value . '">' . $value . '</a>';
    },
    $Artist_Name
);
echo implode(', ', $artist_links);
ghostprgmr
  • 488
  • 2
  • 11
0

This question was asked here and here. However, there are a few ways to do it, for example:

$output = rtrim($string, ',');

EDIT: Having read the comment on this answer it's clear that you don't want to convert to a string. Therefore you can use a counter in your foreach and check when the last one is coming up. When it is, just don't add a ,. Hopefully this helps

Community
  • 1
  • 1
Wouter Vanherck
  • 2,070
  • 3
  • 27
  • 41
0

In order to remove last comma from a string, you can use code below

$lastCommaRemoved = rtrim($Value_new, ',');

UPDATE Original code has many errors, here is fixed one

    <?php
$Artist_Name = array("artist1", "artist2","artist3");
?>
<p class="style18"><b>Artists</b>:
<?php
foreach ($Artist_Name as $_value) {
$Value_new = str_replace(' ', '-', $_value);
    echo '<span class="style24"><a href= "'.BASE_PATH.'artist/'.$Value_new.'">'.$_value.'</a></span>';
}
?>

I should also add, code below does nothing

$Value_new = str_replace(' ', '-', $_value);

Because there is no whitespace in values of $_value variable

Оzgur
  • 432
  • 2
  • 10