How can I remove all empty values when I explode a string using PHP?


The array_filter() or PREG_SPLIT_NO_EMPTY option on preg_split() can be used to remove empty values from a string when it is exploded −

Example

 Live Demo

<?php
$_POST['tag'] = ",abc,defg,,,hijk,lmnop,,0,,";
echo "--- version 1: array_filter ----
"; // note that this also filters "0" out, since (bool)"0" is FALSE in php // array_filter() called with only one parameter tests each element as a boolean value $tags = array_filter( explode(",", $_POST['tag']) ); var_dump($tags); echo "--- version 2: array_filter/strlen ----
"; // this one keeps the "0" element // array_filter() calls strlen() for each element of the array and tests the result as a boolean value $tags = array_filter( explode(",", $_POST['tag']), 'strlen' ); var_dump($tags); echo "--- version 3: PREG_SPLIT_NO_EMPTY ----
"; $tags = preg_split('/,/', $_POST['tag'], -1, PREG_SPLIT_NO_EMPTY); var_dump($tags);  

Output

This will produce the following output −

--- version 1: array_filter ---- array(4) { [1]=> string(3) " abc " [2]=> string(4) " defg " 
[5]=> string(4) "hijk" [6]=> string(5) "lmnop" } --- version 2: array_filter/strlen ---- array(5) 
{ [1]=> string(3) "abc" [2]=> string(4) "defg" [5]=> string(4) "hijk" [6]=> string(5) "lmnop" [8]=> 
string(1) "0" } --- version 3: PREG_SPLIT_NO_EMPTY ---- array(5) { [0]=> string(3) "abc" [1]=> 
string(4) "defg" [2]=> string(4) "hijk" [3]=> string(5) "lmnop" [4]=> string(1) "0" }

Updated on: 09-Apr-2020

914 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements