Reputation: 15007
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.
substr()
to cut of the ,
.write a function to detect the last item and alter the body of the loop to
$str .= $item;
if(!last($item))
$str .= ',';
I think this is good readable, but the programm checks every item if it is the last one, which is obviously only one time the case.
implode(',', $arr)
(But lets assume that this is not possible. Think about a more complex body of the loop)What would be best practice to handle the last (or the first) item in a foreach loop?
Upvotes: 1
Views: 407
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
Reputation:
You can also use rtrim
to remove last unwanted character(s)
$str = rtrim($str, ',');
Upvotes: 0
Reputation: 15113
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
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