1

I have this PHP code:

foreach( $wpdb->get_results(
) as $key => $row) {

echo "['". $row->DATE . "',". $row->total_sales . "],";

}

That produces this:

['09-08-11',0],['09-09-11',0],['09-10-11',0],['09-11-11',0],

How do I remove the last comma in the foreach loop?

1
  • Do not craft a json string manually in a loop. You should populate an array in the loop, the json_encode the array after the loop. Commented Aug 18, 2022 at 8:07

7 Answers 7

14

There are a few approaches:

  1. Push the strings into an array and use implode()
  2. Add the bits to a string, remove the last character, then echo the string
  3. Iterate more explicitly, and on the last iteration, don't output the ','

Of those options, I'd probably use #1, because it makes the code just a bit more self-documenting.

0
6

php has a trim function, give it a string and the comma.

$s = trim ($s,",")
4

You'll need variable to store comma state:

$comma = ""; ## don't need comma before first element
foreach( $wpdb->get_results(
    ) as $key => $row) {

    echo $comma."['". $row->DATE . "',". $row->total_sales . "]";
    $comma = ",";
}
0
1

I usually do it this way..

$result = array();

foreach( $wpdb->get_results() as $key => $row ){

    $result[] = "['". $row->DATE . "',". $row->total_sales . "]";

}

echo implode( ',', $result );

It's a bit more succinct, (but perhaps more memory inefficient due to the temporary array).

1

put your string in substr() function

$string = "";
while ($row = mysql_fetch_array($result)) {
  $string .= $name . ', ';
}
echo substr($string, 0, strlen($string) - 2);
0

I like the implode idea, but I often use the ternary operator to keep everything succinct. Many people don't like the ternary, but it is a very well-known construct in many languages so I use it. In this case, if I'm on the first iteration $results will be empty so I don't insert a comma, otherwise I put a comma in the content before the new data:

$results = '';
foreach( $wpdb->get_results() as $key => $row) {

    $results .= (empty($results) ? '' : ',') . "['". $row->DATE . "',". $row->total_sales . "]";

}
echo $results;
-2
$numItems = count($wpdb->get_results());
$i = 0;

foreach( $wpdb->get_results() as $key => $row) {
if($i+1 == $numItems) {
    echo "['". $row->DATE . "',". $row->total_sales . "]";
  }
else{
echo "['". $row->DATE . "',". $row->total_sales . "],";

}
  $i++;
}
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.