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

How to delete null elements from an array using PHP recursion

怪我咯
怪我咯Original
2017-07-06 09:44:221077browse

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;
}

Demonstration example:

The code is as follows:

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

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!

Statement:
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