开发者

Separating $item with commas

<table>
<开发者_运维问答tr>
<th>Products</th>
</tr>
<td>
                    <? 
                    foreach ($invoice->cart->items as $id => $item) { 
                   ?>
                    <?=$item->getName()?>
                   <?
                        }
                    ?>
                    </td>
</table>

If I have 4 Products then I want to separate with coma ?

For example if I have 4 Products:-

Rubber Ducky™ Gold fish & Tank David Byrne and My Fair Lady - MP3 file download (0 MB)

I want the output with coma like this

Rubber Ducky™, Gold fish & Tank, David Byrne, My Fair Lady MP3 file download (0 MB)

how it is possible with PHP?


<?php
$first = true;
foreach ($invoice->cart->items as $id => $item) {
    if ($first) {
        $first = false;
    } else {
        echo ', ';
    }
    echo $item->getName();
}
?>

This will print a ', ' between item names.

Alternatively, you could also do that:

<?=implode(', ', array_map(function($item) { return $item->getName(); }, $invoice->cart->items))?>


Use implode function. Something like

 $array = $invoice->cart->items;
 echo implode(',',$array);


$i = 0;
foreach( $invoice->cart->items as $item ) {
    echo ($i?', ':'').$item->getName();
    ++$i;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜