Remove empty strings from array in PHP

Are you looking to remove empty items from a PHP array? Here’s a quick snippet for that:

$exclude = "1,2,3,"; //Your string. The trailing comma will leave an empty array entry at the end of the array.
$exclude_array = explode(',', $exclude); //Explode on comma
$exclude_array = array_filter($exclude_array, function($var){
return (trim($var) !== ''); //Return true if not empty string


This will print:

Array ( [0] => 1 [1] => 2 [2] => 3 ) 

Leave a Reply

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

Markdown is allowed in comments.