In this post, I will tell you how to remove empty values from array in PHP by using array_filter
function.
array_filter
function remove all elements from given array that are equal to boolean false and emtpy string always return boolean false.
So question is it that 0 is also return boolean false then array_filter will remove 0 too then how will you keep it in array ?
Example 1: array_filter() function
- $my_array = array(0, "ExpertPHP", "","Demo");
- $resultDirect = array_filter($my_array);
- print_r($resultDirect);
Output :
- Array
- (
- [1] => ExpertPHP
- [3] => Demo
- )
- $my_array = array(0, "ExpertPHP", "","Demo");
- echo "
";- print_r( array_diff( $my_array, array( '' ) ) );
Output:
- Array
- (
- [0] => 0
- [1] => ExpertPHP
- [3] => Demo
- )
array_diff()
function return all the element of first array except element that present in second array.