How to remove the last comma from a PHP foreach loop?

By Faruque Ahamed Mollick

Using PHP foreach loop, we can list the items of an array easily. Also, sometimes we may need to give comma signs after each array. But in English grammar, we should not place the comma sign after the last item. So in this post, we are going to solve this problem.



At first, let’s take an array. Below we have taken an array that contains the list of colors:

 $color_list = array("red", "blue", "black", "green", "yellow", "pink");

Now we want to display each color and try to separate it with a comma after each color name. Below is the PHP code:

 foreach ($color_list as $color) {
    echo $color.", ";
 }

We will see that the comma also appears after the last item of an array:

red, blue, black, green, yellow, pink,

Now, this is not the right thing to keep the comma after the last color item.

Remove the comma from the last item of PHP foreach loop

Now here is the solution. below is the complete PHP code:

<?php

  $color_list = array("red", "blue", "black", "green", "yellow", "pink");

  $num_of_items = count($color_list);
  $num_count = 0;

  foreach ($color_list as $color) {
  	echo $color;
  	$num_count = $num_count + 1;

  	if ($num_count < $num_of_items) {
  		echo ", ";
  	}

  }

?>

Now after we run our code, we will see the result below:

red, blue, black, green, yellow, pink

We can see that, there is no comma sign after the last color item.

An alternative method of removing the comma from last foreach loop item

In this alternative way, we are going to use the PHP array_push() function. below is the code:

<?php

  $color_list = array("red", "blue", "black", "green", "yellow", "pink");

  $color_array = array();

  foreach ($color_list as $color) {
  	  array_push($color_array, $color);
  	}

  echo implode(", ", $color_array);

?>

So we have seen the two ways of removing the comma from the last item of a foreach loop.

Leave a Reply

Your email address will not be published. Required fields are marked *