Kathmandu,Nepal
Kathmandu,Nepal

Remove Empty Values from Array in PHP

We will do it using three different methods:

  1. array_filter() function.
  2. array_diff() functionon.
  3. unset() function.

Method 1: Using array_filter() function:

To remove all the empty values from array, we can use the array_filter() function. This function passes each value of the input array to the callback function. If the callback function returns true, then that value will be added to the returned array otherwise, it will be removed from the array.

In this example, we will removed the empty values from the array using the array_filter() function.

<?php
$array = array("HTML", "CSS", "JavaScript", "", "PHP", "");
$filtered_array = array_filter($array);
print_r($filtered_array);

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

Method 2: Using array_diff() function:

Apart from the array_filter() function, we can also remove the empty values from the array using the array_diff() function. This function is used to compare the values of two arrays or more arrays and returns a new array having the values of the first array, which are not present in other arrays.

In this example, we have removed the empty values from the array using array_diff() function and store the returned value in the new array.

<?php
$language = array("HTML", "CSS", "JavaScript", "", "PHP", "");
$filtered_array = array_diff($language,array(""));
print_r($filtered_array);

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

Method 3: Using unset() function:

In this example, we use to removed the empty values from the array using the unset() function.

<?php
$lang = array("HTML", "CSS", "JavaScript", "", "PHP", "", "jQuery");
foreach($lang as $key => $arr)
{
if($arr === '')
{
unset($lang[$key]);
}
}
print_r($lang);
?>
Output:
Array (
[0] => HTML
[1] => CSS
[2] => JavaScript
[4] => PHP
[6] => jQuery
)

Leave a Comment

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

×