AbcAeffchen
AbcAeffchen

Reputation: 15007

Best practice: Handle first/last item in foreach

Many times I ran into a situation like this

$str = '';
foreach($arr as $item)
{
    $str .= $item . ',';
}

The result would be something like $str = item1,item2,item3,. But I dont want the , at the end.

Now there are some ways to get rid of the ,.
E.g.

What would be best practice to handle the last (or the first) item in a foreach loop?

Upvotes: 1

Views: 407

Answers (4)

AbcAeffchen
AbcAeffchen

Reputation: 15007

This might also be a way:

$last = end($arr);   // returns the last item and sets the internal pointer to the end
unset($arr[key($arr)])   // deletes the last item from the array
$str = '';
foreach($arr as $item)
{
    $str .= $item . ',';
}
$str .= $last;

This does not check or assign anything additional in the loop, but I think it is not a good readable way.

Upvotes: 0

user3912348
user3912348

Reputation:

You can also use rtrim to remove last unwanted character(s)

$str = rtrim($str, ',');

Upvotes: 0

In languages that do not have a join-like method, this is what I've used (and seen used) for a while.

result = ""
delim = ""
foreach(string in array)
   result += delim + string
   delim = ","

(Apply to your favorite language)

In your case using PHP, it would look like

$str = "";
$delim = "";
foreach($arr as $item) {
    $str .= $delim + $item;
    $delim = ",";
}

Upvotes: 6

Ricky
Ricky

Reputation: 384

Follow this Example it may solve your hurdle.

$arr = array(1,2,3,4,5,6,7);
$copy = $arr;
foreach ($arr as $val) {
    echo $val;
    if (next($copy )) {
        echo ','; // Add comma for all elements instead of last
    }
}

Upvotes: 0

Related Questions