tags:

views:

431

answers:

6

Simple one guys.

I have an XML parsed using simplexml_load_file().

The following code:

<?php
    foreach($xml->actors->actor as $actors) {
        echo $actors.", ";
    }
?>

Gives the following result:

John Smith, Amy Adams, Charlie Doe,

How do I modify the code such that it gives:

John Smith, Amy Adams, Charlie Doe

This needs to apply across any number of entries in the array. Thanks!

A: 

I usually solve this problem with a simple array:

<?php
$names = array();
foreach($xml->actors->actor as $actors) {
    $names[] = $actors;
}
echo implode(", ", $names);
?>

As a matter of fact why not just say

<?php
    echo implode(", ", $xml->actors->actor);
?>
Marek Karbarz
1) foreach($xml->actors->actor as $actors) {echo $actors.", ";}2) echo implode(',',$xml->actors->actor);Ran into a snag. First one outputs correctly, second one gives me an "invalid arguments" error. Any ideas? Thanks.
RC
+1  A: 
print implode(',',$xml->actors->actor);
Chris Kloberdanz
lo_fye
A: 

You can get the current index in a foreach:

<?php
    foreach($xml->actors->actor as $key => $actors) {
     if ($key == (count($actors)-1) echo "Last entry!";
    }
?>

In cases like this, however, I prefer to create a temporary array with the entries first, and then implode it:

echo implode(",", $names);
Pekka
+5  A: 

Use the implode function.

echo implode(", ", $xml->actors->actor);
Mikael S
It seems there's a consensus! Thanks all - didn't know such a function existed.
RC
A: 

Did you try This solution ?

Soufiane Hassou
A: 

You can either implode the array as many people above have suggested, or assign the actor's names to a variable and concatenate that variable with each iteration, and then perform a rtrim operation on the resulting array to remove the last comma.

But for simplicity's sake, go with an implode.

Martin Bean