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']);
?>