Delete Trailing Comma

Issue

I am using a multidimensional array and trying to echo all car models of one particular make within an array. I have the following code:

<?php
$cars = array( 
              "Dodge"  => array("Avenger","Challenger","Charger","Dart"),
              "Toyota" => array("Highlander","Tundra","Corolla"),
              "Nissan" => array("Sentra","Altima","Maxima")
        );

echo "Make: Toyota"; echo "<br><br>";

foreach($cars['Toyota'] as $x)

{
$cars['Toyota'] = rtrim($x, ',');
echo "$x, ";
}

?>

Clearly my most recent shot at this was using the rtrim function but that didn’t work for me. Also tried implode function to no success. May I have some help here?

Solution

You issue is that you are putting the trailing comma in there yourself. Try something like this:

<?php
$cars = array( 
          "Dodge"  => array("Avenger","Challenger","Charger","Dart"),
          "Toyota" => array("Highlander","Tundra","Corolla"),
          "Nissan" => array("Sentra","Altima","Maxima")
    );

echo "Make: Toyota"; 
echo "<br><br>";

$first = TRUE;
$carString = '';
foreach($cars['Toyota'] as $x){
    if ($first){
        $carString .= $x;
        $first = FALSE;
    }else{
        $carString .= ", $x";
    }
}
echo $carString;
?>

If you want a simpler loop, without the control structures (I felt it useful to demonstrate what is really going on in the loop), then you can use rtrim after looping, like this:

<?php
$cars = array( 
          "Dodge"  => array("Avenger","Challenger","Charger","Dart"),
          "Toyota" => array("Highlander","Tundra","Corolla"),
          "Nissan" => array("Sentra","Altima","Maxima")
    );

echo "Make: Toyota"; 
echo "<br><br>";

$carString = '';
foreach($cars['Toyota'] as $car) {
   $carString .= $car.',';
}
echo rtrim($carString, ',');
?>

if you don’t need to loop through for anything other than building the string, you can just implode the array to print it:

<?php
$cars = array( 
          "Dodge"  => array("Avenger","Challenger","Charger","Dart"),
          "Toyota" => array("Highlander","Tundra","Corolla"),
          "Nissan" => array("Sentra","Altima","Maxima")
    );

echo "Make: Toyota"; 
echo "<br><br>";
echo implode(', ', $cars['Toyota']);
?>

Answered By – bubba

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published