0

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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 3
    How about `echo implode(',', $cars['Toyota']);`? – N.B. Sep 11 '13 at 16:54
  • I'm slightly confused. Are you complaining about the ending comma in what has been echoed out? If that is the case, it is because you are explicitly doing `echo "$x, " which will ALWAYS give a comma. – Justin Wood Sep 11 '13 at 16:56
  • That's close! But, it returns as "Make: Toyota Highlander,Tundra,CorollaHighlander,Tundra,CorollaHighlander,Tundra,Corolla" So it returns without the trailing comma, but prints out 3 times in a row... probably because there are three values in that particular array... so it still a problem. – user2769624 Sep 11 '13 at 16:56
  • Justin Wood, that is true. But I want the items to be separated by commas. – user2769624 Sep 11 '13 at 16:57
  • You didn't tell us how the output is supposed to be formatted. I just gave you an idea how you can do it without looping and having an issue with last element having that comma. Also, you shouldn't use that implode function within loop. You don't need the loop. – N.B. Sep 11 '13 at 16:57
  • Use more professional techniques than making a mess and then cleaning it up after the loop. https://3v4l.org/K7FCo – mickmackusa Jun 15 '22 at 04:03

2 Answers2

2

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']);
?>
bubba
  • 3,839
  • 21
  • 25
  • Even though I gave my own answer, I upvoted this one because `echo implode...` avoids the loop, and it's cleaner code. – TecBrat Sep 11 '13 at 17:07
  • I started to do this as an edit, but I'll leave that up to you and the OP, but you might want `implode(', ', $cars['Toyota']); ` – TecBrat Sep 11 '13 at 17:10
  • I would prefer to keep it as a loop. Might not need to be in this case... but I am trying to learn loops in case I need to use one later. So I will try out your first answer, but it seems like a lot of code for a trailing comma fix. – user2769624 Sep 11 '13 at 17:11
  • It worked Bubba! You're answer with the rtrim function worked and I believe that would be the one I prefer, though I am still learning... I will be using foreach loops in the future so I may not have needed it here, but I might later right? Thank you so much, and I can't upvote you now because I don't have 15 rep yet... really sorry :( – user2769624 Sep 11 '13 at 17:23
  • But you asked the question, you can mark it as the selected answer, no? – bubba Sep 11 '13 at 17:25
  • Marked as correct! Thank you very much for the help Bubba! One last thing if you have time... the car names echo out correctly with no trailing comma, but how can I have a space inserted after each comma? Right now it prints as "Highlander,Tundra,Corolla" with no spaces. Thanks! – user2769624 Sep 11 '13 at 17:34
  • @Bubba... I have been trying to add that space for like an hour now... Anyway you can help?? – user2769624 Sep 11 '13 at 18:59
  • You mean like this? echo implode(', ', $cars['Toyota']); – bubba Sep 11 '13 at 19:05
  • @Bubba SOLVED. You rule. – user2769624 Sep 11 '13 at 19:22
0

I think this is what you really want:

foreach($cars['Toyota'] as $key=>$x)
{
echo $x;
if($cars['Toyota'][$key+1]){echo ', ';}
}
TecBrat
  • 3,643
  • 3
  • 28
  • 45
  • This is pretty much what I am looking for. But, it still echos with the trailing comma :( I used your code exactly. I am testing with phpfiddle.org btw.... – user2769624 Sep 11 '13 at 17:08
  • 1
    I tested my code at http://writecodeonline.com/php/ and it worked perfectly. But, I'd suggest @Bubba's solution instead. You implode the array and echo it. – TecBrat Sep 11 '13 at 17:13
  • I will test it there now. I like Bubba's solutions too, but I want to keep it as a loop for learning purposes. Will it still work then? – user2769624 Sep 11 '13 at 17:17
  • Thank you very much for the help TecBrat. Bubba's solution with the rtrim function finally worked for me. Yours probably works fine too, just couldn't make it correctly in my case. Thanks for helping me!! – user2769624 Sep 11 '13 at 17:30