Recursive array iterator

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
dibyendrah
Forum Contributor
Posts: 491
Joined: Wed Oct 19, 2005 5:14 am
Location: Nepal
Contact:

Recursive array iterator

Post by dibyendrah »

Dear all,

I want to develop a function which will recursively clean an array having empty values.

Suppose I have created array like following :

Code: Select all

<?php

$x = array("a"=>array("a1"=> "", "a2"=> 1, "a3"=> 2), "b" => 0, "c"=>array("c1"=>1, "c2"=>""), "d"=>array("d1"=>array("d1a"=>"", "d1b"=>"")));

print_r($x);

?>
Output :

Code: Select all

Array
(
    [a] => Array
        (
            [a1] => 
            [a2] => 1
            [a3] => 2
        )

    [b] => 0
    [c] => Array
        (
            [c1] => 1
            [c2] => 
        )

    [d] => Array
        (
            [d1] => Array
                (
                    [d1a] => 
                    [d1b] => 
                )

        )

)
Hope somebody has already given effort to solve this kind of porblem using recursive array iterator.

With Best Regards,
Dibyendra Hyoju
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

try

Code: Select all

function array_rfilter(&$arr, $callback) {
	foreach($arr as $i=>$e) {
		if (is_array($e)) {
			$arr[$i]=array_rfilter($e, $callback);
		}
	}
	return array_filter($arr, $callback);
}
	
function notempty($a) {
	return !empty($a);
}

$x = array("a"=>array("a1"=> "", "a2"=> 1, "a3"=> 2), "b" => 0, "c"=>array("c1"=>1, "c2"=>""), "d"=>array("d1"=>array("d1a"=>"", "d1b"=>""))); 
print_r(array_rfilter($x, 'notempty'));
(adhoc function, not well tested)
User avatar
dibyendrah
Forum Contributor
Posts: 491
Joined: Wed Oct 19, 2005 5:14 am
Location: Nepal
Contact:

Post by dibyendrah »

Thanks Volka for your great effort. It worked well. Never used the callback function before.

Dibyendra
Post Reply