Remove empty array elements in PHP

array_filter

$arr = array("PHP", "HTML", "CSS", "", "JavaScript");

print_r($arr);

/*
Output: 
Array
(
    [0] => PHP
    [1] => HTML
    [2] => CSS
    [3] => 
    [4] => JavaScript
)
*/

A quick solution to remove empty elements from an array is using array_filter without a callback function. This will also remove blank, null, false, 0 (zero).

$filterArray = array_filter($arr);

print_r($filterArray);

/*
Output:
Array
(
    [0] => PHP
    [1] => HTML
    [2] => CSS
    [4] => JavaScript
)
*/

array_values

If you are working with a numerical array and need to re-indexes the array after removing empty elements, use the array_values function. array_values returns all the values from the array and indexes the array numerically.

$myArray = array_values(array_filter($arr));

print_r($myArray);

/*
Output:
Array
(
    [0] => PHP
    [1] => HTML
    [2] => CSS
    [3] => JavaScript
)
*/
Leave a reply
Captcha Click on image to update the captcha .