Display array of links as string separated by commas using implode

I’m trying to display an array of href links as a string with the results separated by commas so as to display:-
I Am The Walrus, [URL=“http:///song/55/hello-goodbye”]Hello, Goodbye, [URL=“http:///song/56/the-fool-on-the-hill”]The Fool On The Hill, [URL=“http:///song/57/magical-mystery-tour”]Magical Mystery Tour, [URL=“http:///song/58/lady-madonna”]Lady Madonna
(NB: Some results will contain commas (Hello, Goodbye) so I’ll need to use the ‘implode’ function rather than ‘preg_replace’).

The links are comprised of three different values from each result, i.e. ‘id’ and ‘url’ for the URL and ‘name’ for the name to be displayed.

My current code:
Index:-

<?php
while ($row = mysqli_fetch_array($result)) //Creates array.
{
	$songs[] = array('id' => $row['id'], 'url' => $row['url'], 'name' => $row['name']);
}
?>

Display page:-

<?php foreach ($songs as $song)
{
$song = '<a href="/song/' . $song['id'] . '/' . $song['url'] . '">' . $song['name'] . '</a>';
}
echo implode(", ", $songs);
?>

Outputs:-

Notice: Array to string conversion in C:\

Notice is repeated x 5 times (i.e. however many results there are)

Followed by the below:-

Array, Array, Array, Array, Array

Again, repeated according to number of results.

The method was taken from this problem: PHP Separate comma list with links, but it only requires the one value to create the link; mine needs three.

I feel all I require to make this work is a minor tweak but I just can’t figure it out – any suggestions?

You’re re-assigning the $song array variable to a new string value upon each iteration in the foreach loop; which will achieve nothing. You’re then imploding the original $songs variable, which again will not work, because you have a multi-dimensional array, meaning that you’re echoing out each sub-array (with the keys: id, url, and name).

Try this:


$songsList = array();

foreach($songs as $song) {
	$songsList[] = '<a href="/song/' . $song['id'] . '/' . $song['url'] . '">' . $song['name'] . '</a>';
}
echo implode(", ", $songsList);

It works - thanks SO much!