Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implode foreach

How to implode foreach() with comma?

foreach($names as $name) {
    //do something
    echo '<a href="' . $url . '" title="' . $title . '">' . $name .'</a>';
}

Want to add comma after each link, except the last one.

like image 257
James Avatar asked Sep 02 '10 10:09

James


3 Answers

Raveren's solution is efficient and beautiful, but here is another solution too (which can be useful in similar scenarios):

$elements = array();
foreach($names as $name) {
    //do something
    $elements[] = '<a href="' . $url . '" title="' . $title . '">' . $name .'</a>';
}
echo implode(',', $elements);
like image 67
Emil Vikström Avatar answered Oct 19 '22 10:10

Emil Vikström


You need to transform your array instead of iterating using foreach. You can do this with array_map.

PHP 5.3 syntax with closures

echo implode(", ", array_map(function($name) use($url, $title)
{
    return '<a href="' . $url . '" title="' . $title . '">' . $name .'</a>';
}, $names));

Compatible syntaxe before PHP 5.3

function createLinkFromName($name)
{
    return '<a href="' . $url . '" title="' . $title . '">' . $name .'</a>';
}
echo implode(", ", array_map('createLinkFromName', $names));

PHP 5.3 syntax with a better reability

function a_map($array, $function)
{
    return array_map($function, $array);
}

echo implode(", ", a_map($names, function($name) use($url, $title)
{
    return '<a href="' . $url . '" title="' . $title . '">' . $name .'</a>';
}));
like image 33
Vincent Robert Avatar answered Oct 19 '22 10:10

Vincent Robert


$first = TRUE;
foreach($names as $name) {
    //do something
    if(!$first) { echo ', '; }
    $first = FALSE;
    echo '<a href="', $url, '" title="', $title, '">', $name, '</a>';
}
like image 3
knittl Avatar answered Oct 19 '22 10:10

knittl