Reputation: 353
Is there other way to trim this inside the loop? I have a loop and inside, i need to rtrim the last loop row, but what happen is it removes all character each of the last right string.
If I use this method, it works.
$plus = "";
for($i=0; $i<6; $i++){
$plus .= 'total'.$i."+";
}
echo rtrim($plus,'+');
//output
total0+total1+total2+total3+total4+total5
But how if i need to rtrim it inside the loop? Because I need for some reason
for($i=0; $i<6; $i++){
$plus = 'total'.$i."+";
echo rtrim($plus,'+');
}
//output says
total0total1total2total3total4total5
//This should be like
//total0+total1+total2+total3+total4+total5
Upvotes: 0
Views: 197
Reputation: 1455
Hope it helps.
for($i=0; $i<6; $i++){
$plus .= 'total'.$i.'+';
if($i == 5){
echo rtrim($plus,'+');
}
}
Upvotes: 1
Reputation: 7617
Here would be another approach without a need for trim()
or implode()
:
$plus = "";
for($i=0; $i<6; $i++){
$plus .= 'total'. $i;
if($i < 5){
$plus .= "+";
}
}
echo $plus;
Upvotes: 2
Reputation: 78994
That makes no sense. If you don't want the last +
then rtrim()
after the loop, why inside?
Just create an array and implode()
:
for($i=0; $i<6; $i++){
$plus[] = 'total'.$i;
}
$plus = implode('+', $plus);
Upvotes: 3