Skip to main content

PHP – Remove an Item From a Comma Separated String

Sometimes we need to remove specific item from comma separated string. Here is a running PHP function to remove an item from a comma-separated string. The function will remove the selected item from the string and return the remaining parts of the string.

view plaincopy to clipboardprint?

  1. <?php
  2. function removeItemString($str, $item) {
  3. $parts = explode(‘,’, $str);
  4. while(($i = array_search($item, $parts)) !== false) {
  5. unset($parts[$i]);
  6. }
  7. return implode(‘,’, $parts);
  8. }
  9. $mystring =‘cat,mouse,dog,horse’;
  10. $result_string = removeItemString($mystring, “mouse”);
  11. echo “Input String: “.$mystring;
  12. echo “</br>”;
  13. echo “Output String: “.$result_string;
  14. ?>

Input String: cat,mouse,dog,horse
Output String: cat,dog,horse

PHPZAG.COM is a popular PHP tutorial blog that publishes useful tips and tutorials for PHP programmer. If you would like to be kept up to date with our posts, you can subscribe to our RSS Feed

Leave a Reply

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


Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!