Saturday, 10 January 2015

Php for each with comma separator except last


Sometimes we write a logic to show comma separated data. But the challenge is not to append comma to the last value.
We can do this by using next() function:
 
<?php
$arr = array('tvs','hero','honda','bajaj');
$copy = $arr;
foreach ($arr as $val) {
    echo $val;
    if (next($copy )) {
        echo ','; // Add comma for all elements instead of last
    }
}
?>