Tips.PHP: Removing empty strings, NULL, FALSE, and negative numbers from Array

Often we need to remove empty elements from our array. For example when we split a string with space, we can get the words and also blank strings when there are two or more spaces put together.

We can use array_filter function for rescue. When we call array_filter with out passing the filter function it removes all values that evaluate to FALSE.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php
$string = "I love   Luracast Restler 2.0";
$words = explode(' ', $string);
print_r($words);
/* outputs the following
Array
(
    [0] => I
    [1] => love
    [2] =>
    [3] =>
    [4] => Luracast
    [5] => Restler
    [6] => 2.0
)
*/

$words = array_filter($words);
print_r($words);
/* outputs the following
Array
(
    [0] => I
    [1] => love
    [4] => Luracast
    [5] => Restler
    [6] => 2.0
)
*/

4 comments

Leave a Reply