Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How can I remove all empty values when I explode a string using PHP?
When exploding a string in PHP, you often need to remove empty values from the resulting array. There are three main approaches: using array_filter(), using array_filter() with strlen, or using preg_split() with the PREG_SPLIT_NO_EMPTY flag.
Using array_filter()
The simplest approach uses array_filter() to remove falsy values, but this also removes "0" since it evaluates to false −
<?php
$string = ",abc,defg,,,hijk,lmnop,,0,,";
echo "Original string: " . $string . "<br><br>";
echo "--- Using array_filter() ---<br>";
$result = array_filter(explode(",", $string));
var_dump($result);
?>
Original string: ,abc,defg,,,hijk,lmnop,,0,,
--- Using array_filter() ---
array(4) {
[1]=>
string(3) "abc"
[2]=>
string(4) "defg"
[5]=>
string(4) "hijk"
[6]=>
string(5) "lmnop"
}
Using array_filter() with strlen
To preserve "0" values while removing empty strings, use strlen as the callback function −
<?php
$string = ",abc,defg,,,hijk,lmnop,,0,,";
echo "--- Using array_filter() with strlen ---<br>";
$result = array_filter(explode(",", $string), 'strlen');
var_dump($result);
?>
--- Using array_filter() with strlen ---
array(5) {
[1]=>
string(3) "abc"
[2]=>
string(4) "defg"
[5]=>
string(4) "hijk"
[6]=>
string(5) "lmnop"
[8]=>
string(1) "0"
}
Using preg_split() with PREG_SPLIT_NO_EMPTY
The preg_split() function with PREG_SPLIT_NO_EMPTY flag removes empty values during splitting and reindexes the array −
<?php
$string = ",abc,defg,,,hijk,lmnop,,0,,";
echo "--- Using preg_split() with PREG_SPLIT_NO_EMPTY ---<br>";
$result = preg_split('/,/', $string, -1, PREG_SPLIT_NO_EMPTY);
var_dump($result);
?>
--- Using preg_split() with 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"
}
Comparison
| Method | Preserves "0" | Reindexed Array | Performance |
|---|---|---|---|
array_filter() |
No | No | Fast |
array_filter() + strlen |
Yes | No | Medium |
preg_split() + flag |
Yes | Yes | Medium |
Conclusion
Use array_filter() with strlen to preserve "0" values while keeping original indices. Use preg_split() with PREG_SPLIT_NO_EMPTY when you need a reindexed array without empty values.
