Sam Healey
Sam Healey

Reputation: 676

foreach statement rewrite last element?

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

Answers (8)

Havelock
Havelock

Reputation: 6966

You can use rtrim() to do this

rtrim($string, ',');
echo $string;

should do the job.

Upvotes: 2

Mahn
Mahn

Reputation: 16605

Easiest way:

foreach($album as $a){ 
    $string .= $a['value'].', ';
}

$string = substr($string, 0, -2);
echo $string;  

More on substr here

Upvotes: -1

Dave Lasley
Dave Lasley

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

Piotr Olaszewski
Piotr Olaszewski

Reputation: 6204

Try:

$string = preg_replace('#, $#', '', $string);

Upvotes: -1

nunespascal
nunespascal

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

bcmcfc
bcmcfc

Reputation: 26795

You could use implode():

$values = array();
foreach ($album as $a){
  $values[] = $a['value'];
}

$string = implode(',', $values);

Upvotes: 6

Mark Baker
Mark Baker

Reputation: 212452

$first = TRUE;
$string = '';
foreach($album as $a) {  
    if ($first) {
        $first = FALSE;
    } else {
        $string .= ', ';
    }
    $string .= $a['value']; 
} 

Upvotes: 0

tradyblix
tradyblix

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

Related Questions