I am running this foreach loop. I need to seperate each value by a comma, which this does. However, I need to kill the comma on the last value.

foreach ($_POST as $key=>$value){
	
if ($key != "submit" && $key != "type"){
		
$fields = $key.",";
echo $fields;
		
}
}

This returns this:

name,title,organization,city,state,

I need it to return this:

name,title,organization,city,state

NO COMMA AFTER THE LAST VALUE, WHICH ISNT ALWAYS STATE.

I tired rtrim and ltrim but it removes all the commas.

Thanks in advance.

$fields = substr($fields,0,strlen($fields)-1);

Thanks for the help, but it took all the commas out, not just the last one:

This is what it returned:

nametitleorganizationcitystate

tried and tested.
<?php

foreach($_GET as $val){
$x++;
}

foreach($_GET as $val){
$y++;
if($y<$x){
echo $val.",";
}else{
echo $val;
}
}

?>

please mark this solved, if you think we solved it... thanks

i forgot to use bbcode sorry... hehe

foreach($_GET['chk'] as $val){
$x++;
}

foreach($_GET['chk'] as $val){
$y++;
if($y<$x){
echo $val.",";
}else{
echo $val;
}
}
$fields = substr($fields,0,strlen($fields)-1);

Thanks for the help, but it took all the commas out, not just the last one:

This is what it returned:

nametitleorganizationcitystate

uhhhh.


put it on line 11. it will only take the last one off.


My bad, I thought it was pretty clear where to put it based off of what it was doing.

Try this...

$comma = "";

foreach ($_POST as $key=>$value){
	
	if ($key != "submit" && $key != "type"){
			
		$fields = $comma.$key;
		
		echo $fields;
		
		$comma = ",";
			
	}
}
<?
$fields="";
foreach ($_POST as $key=>$value)
{
	
	if ($key != "submit" && $key != "type")
	{
		$fields	=	($fields!="")?$fields.",".$key:$key;
	}
}
echo $fields;
?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.