php

How to remove empty elements from array

You can simply use the PHP array_filter() function to remove or filter empty values or elements from an array. This function typically filters the values of an array using a callback function.

However, if no callback function is specified, all empty entries of array will be removed, such as “” (an empty string), 0 (0 as an integer), 0.0 (0 as a float), “0” (0 as a string), NULL, FALSE and array() (an empty array). Let’s try out an example to understand how it actually works:

<?php
$array = array(
'key1'=>'value1',
'key2'=>'value2',
'key3'=>'value3',
'key4'=>' ',
'key5'=>' ',    
'key6'=>null,    
);
$filterArray = array_map('trim',$array);
$filterArray = array_filter($filterArray);

print_r($filterArray);//Array ( [key1] => value1 [key2] => value2 [key3] => value3 );
?>

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button