Home > Article > Backend Development > How to delete empty array recursively in php
php method to recursively delete empty arrays: first create a PHP sample file; then delete all empty value elements in the array through the "function array_remove_empty($arr){...}" method.
The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer
php recursively calls to delete array null elements The method
The example of this article describes the method of php recursively calling to delete the null value element of the array. Share it with everyone for your reference. The details are as follows:
This function can delete all null 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)
[Recommended learning: PHP video tutorial]
The above is the detailed content of How to delete empty array recursively in php. For more information, please follow other related articles on the PHP Chinese website!