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.

<?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
)
*/

One comment

Leave a Reply