0

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.

Edited by Morty222: n/a

5
Contributors
7
Replies
8
Views
7 Years
Discussion Span
Last Post by arunss
0
$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

0

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

0

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;
}
}
0
$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.

0

Try this...

$comma = "";

foreach ($_POST as $key=>$value){
	
	if ($key != "submit" && $key != "type"){
			
		$fields = $comma.$key;
		
		echo $fields;
		
		$comma = ",";
			
	}
}
0
<?
$fields="";
foreach ($_POST as $key=>$value)
{
	
	if ($key != "submit" && $key != "type")
	{
		$fields	=	($fields!="")?$fields.",".$key:$key;
	}
}
echo $fields;
?>
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.