Reputation: 676
Im using foreach as below
foreach($album as $a) {
$string .= $a['value'].', ';
}
echo $string;
which returns something like
1, 2, 3,
etc
now how do I remove the , from the last loop.
So $string returns 1, 2, 3
Upvotes: 0
Views: 303
Reputation: 6966
You can use rtrim()
to do this
rtrim($string, ',');
echo $string;
should do the job.
Upvotes: 2
Reputation: 16605
Easiest way:
foreach($album as $a){
$string .= $a['value'].', ';
}
$string = substr($string, 0, -2);
echo $string;
More on substr here
Upvotes: -1
Reputation: 6282
if you don't want to use implode()
, which is the best method, you can create a temp var:
foreach($album as $a){
$string .= $addStr . $a['value'];
$addStr = ',';
}
Upvotes: 0
Reputation: 17724
A for loop would be better suited in this case, so that you could just avoid adding it for the last element.
But you can just trim the string to the right.
Upvotes: 0
Reputation: 26795
You could use implode()
:
$values = array();
foreach ($album as $a){
$values[] = $a['value'];
}
$string = implode(',', $values);
Upvotes: 6
Reputation: 212452
$first = TRUE;
$string = '';
foreach($album as $a) {
if ($first) {
$first = FALSE;
} else {
$string .= ', ';
}
$string .= $a['value'];
}
Upvotes: 0
Reputation: 7579
Maybe you could do something like this:
$value = array();
foreach($album as $a) {
array_push($value, $a['value']);
}
echo join(',', $value); // join by comma
Upvotes: 3