This article demonstrates how to remove empty elements from an array in PHP.

1. Using array_filter() function

The array_filter() function removes all falsy values from the array if no callback function is supplied. The falsy value in PHP are boolean false, integer 0, float 0.0 and -0.0, string "0" and "", unit type NULL, and an empty array. It should be noted that the resource variable and NAN are not considered falsy in PHP.

Download  Run Code

 
If the callback function is provided, only entries in the array that don’t satisfy the supplied predicate will be removed. For example, the following code removes only empty strings ("") and NULL values from the array.

Download  Run Code

 
The expression array_filter($arr) is equivalent to array_filter($arr, function($val){return !empty($val);}). You can add or remove elements from the predicate as needed. For example, the following includes 0 from the falsy values.

Download  Run Code

 
You can use the array_filter() function to remove only a particular element from the array. For example, the following removes only empty strings ("") from the array.

Download  Run Code

 
You can also use array_filter() using PHP’s built-in functions as your callback. For example, the following solution uses the strlen() function as a callback and removes empty strings (""), false, and NULL from the array, but ignores true, 0, 0.0, and "0". This is because thestrlen() function returns a zero value for "", false, and NULL, but a non-zero value for true, 0, 0.0, and "0".

Download  Run Code

2. Using array_diff() function

Alternatively, you can use the array_diff() function to remove empty elements from an array. It computes the difference between arrays and returns the values present only in the input array, but not in any of the other arrays.

However, it compares the string representation of elements. i.e., two elements $x and $y are considered equal if and only if (string)$x === (string)$y.

Download  Run Code

That’s all about removing empty elements from an array in PHP.