Categories
PHP

PHP Program to remove empty or specific array elements.

This tutorial is created to remove specific or empty (NULL) array elements from the array.

  1. array_filter() to Remove Empty Elements

array_filter() function removes false values when declared using a callback function, however, If the callback function returns true, the current value from input is returned into the result array.

  1. $array (mandatory): This is where the input array is given.
  2. $callback_function (optional): The user-defined function is given . If the function is not given then all entries of the array equal to FALSE and will be removed.
  3. $flag (optional): The arguments passed to the callback function is defined.
    • ARRAY_FILTER_USE_KEY β€“ Only key argument is passed to the callback function, instead of the value of the array.
    • ARRAY_FILTER_USE_BOTH β€“ Both value and key as arguments to callback instead of the value.

Syntax :

array array_filter($array, $callback_function, $flag)
Code language: PHP (php)

Below is a program showing how to return filtered array elements using array_filter() function.

<?php
// Declaring the array
$array = array("bishrul", 27, '', null, "developer", 45,"for", 1994, false,);

// Function to remove empty elements
$filtered_array = array_filter($array);

// Display the array
var_dump($filtered_array);
Code language: HTML, XML (xml)

Output :

array(6) { [0]=> string(7) "bishrul" [1]=> int(27) [4]=> string(9) "developer" [5]=> int(45) [6]=> string(3) "for" [7]=> int(1994) }
Code language: PHP (php)
  1. unset() Function to Remove Empty Elements.

The Another way is to remove empty elements from array is using empty() function along with the unset() function. The empty() function is used to check whether the element is empty is not.

<?php
// Declaring the array
$array = array("bishrul", 27, '', null, "developer", 45,"for", 1994, false,);

// Loop to find empty elements
foreach($array as $key => $value)
  if(empty($value)){
  unset($array[$key]);
}

// Displaying the array
foreach($array as $key => $value)
    echo ($array[$key] . " , ");
?> 
Code language: HTML, XML (xml)

Output :

bishrul , 27 , developer , 45 , for , 1994 ,

Removing a specific value using unset() function in PHP.

<?php
// Declaring the array
$array = array("bishrul", 27, '', null, "developer", 45,"for", 1994, false,);

// Loop to find empty elements
foreach($array as $key => $value)
  if($value == "bishrul"){
  unset($array[$key]);
}

// Displaying the array
foreach($array as $key => $value)
    echo ($array[$key] . " , ");
?> 
Code language: HTML, XML (xml)

Output :

27 , , , developer , 45 , for , 1994 , ,

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.

Leave a Reply

Your email address will not be published.