JavaOgreniyor
JavaOgreniyor

Reputation: 31

Remove the last part of the comma in foreach in PHP?

How can I prevent the insertion of a comma at the end of the title3?

foreach ($_POST['titles'] AS $title) {
    echo "{$title},";
}; 

Result:

title1,title2,title3,

Update : It comes as a form data, this is array. Don't come this way; title1,title2,title3,

<form>
<select name="titles[]">
<option>title1</title>
<option>title2</title>
<option>title3</title>
<option>title4</title>
</select>
</form>

Upvotes: 0

Views: 123

Answers (4)

TCooper
TCooper

Reputation: 1910

I agree with the other answers - implode() is the way to go. But if you'd rather not/keep on the path you're on...

$output = "";
foreach ($_POST['titles'] AS $title) {
    $output .= "{$title},";
};
echo substr($output, 0, -1);

Upvotes: 0

pew007
pew007

Reputation: 483

You should use implode instead.

$string = implode(',', $_POST['titles']);

Upvotes: 0

Martin Zeitler
Martin Zeitler

Reputation: 76849

just use implode() - which is the equivalent to .join():

echo implode(',', $_POST['titles']);

or simply:

echo implode($_POST['titles']);

if you really want to use a loop - an index is required in order to determine the last one element. a foreach loop does not provide any index to compare to; that's why a for loop is rather suitable:

// $titles = explode(',', $_POST['titles']);
$titles = $_POST['titles'];
for($i=0; $i < sizeof($titles); $i++) {
    echo $titles[$i];
    if($i+1 != sizeof($titles)){echo ',';}
}

Upvotes: 7

user10051234
user10051234

Reputation:

looks like you could skip the foreach altogether and just do this:

echo implode(',',$_POST['titles']);

Upvotes: 3

Related Questions