Home > Backend Development > PHP Tutorial > How to delete null elements from an array using PHP recursion

How to delete null elements from an array using PHP recursion

怪我咯
Release: 2023-03-12 19:32:01
Original
1084 people have browsed it

This article mainly introduces the method of phprecursioncallingdeletearraynull value elements, involving the related skills of php recursive calling to operate the array, which is very useful For practical value, friends in need can refer to

This article describes the method of recursively calling PHP to delete empty elements in an array. Share it with everyone for your reference. The details are as follows:

This function can delete all null value elements in the array, including empty strings, empty arrays, etc.

function array_remove_empty($arr){
 $narr = array();
 while(list($key, $val) = each($arr)){
  if (is_array($val)){
   $val = array_remove_empty($val);
   // does the result array contain anything?
   if (count($val)!=0){
    // yes :-)
    $narr[$key] = $val;
   }
  }
  else {
   if (trim($val) != ""){
    $narr[$key] = $val;
   }
  }
 }
 unset($arr);
 return $narr;
}
Copy after login

Demonstration example:

The code is as follows:

array_remove_empty(array(1,2,3,'',array(),4)) => returns array(1,2,3,4)
Copy after login

The above is the detailed content of How to delete null elements from an array using PHP recursion. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template