user4099673
user4099673

Reputation:

Remove last comma during an explode in PHP

How to ignore the last comma inserted ?

<?php
$moods = "pizza1,pizza2,pizza3,";
$moodList = explode(",", $moods);
print_r($moodList);
?>

Upvotes: 0

Views: 1608

Answers (3)

Tim
Tim

Reputation: 2163

How about using substr() to cut out the last comma?

// Your string
$str = "pizza1,pizza2,pizza3,";
// The $num is the string length, minus 1 (b/c you're cutting the last character out in substr)
$num = strlen($str) - 1;
// Cut the last character with substr
$edited_str = substr($str, 0, $num);
// The result
echo $edited_str;

EDIT

As Mark Baker has pointed out, you can simply use $str = substr($str, 0, -1); instead of counting the string length. So

// Your string
$str = "pizza1,pizza2,pizza3,";
// Cut the last character with substr
$edited_str = substr($str, 0, -1);
// The result
echo $edited_str;

Upvotes: 0

Buttle Butkus
Buttle Butkus

Reputation: 9476

$moodlist = explode(',',trim($moods,','));

Just trim commas.

Upvotes: 7

Samer Allahham
Samer Allahham

Reputation: 76

You Can Ignore it like this

<?php
$moods = "pizza1,pizza2,pizza3,";
$moodList = explode(",", substr($moods,0,strlen($moods)-1));
print_r($moodList);
?>

Upvotes: 0

Related Questions