Saturday 10 January 2015

Php for each with comma separator except last

Posted by Shiva on 02:48 in , | No comments

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
    }
}
?>

0 comments:

Post a Comment