2

I have post data that looks like this:

array(2) { 
    ["ui"]=> array(1) { 
        ["menu"]=> array(3) { 
            ["button1"]=> string(8) "Press me" 
            ["button2"]=> string(9) "Tickle me"
            ["button3"]=> string(0) ""

        }
    }
    ["messages"]=> array(1) { 
        ["status"]=> array(2) { 
            ["error"]=> string(0) "" 
            ["success"]=> string(0) ""
        }
    }
}

I want to remove all key, value pairs that have an empty value to get a result like this:

 array(1) { 
    ["ui"]=> array(1) { 
        ["menu"]=> array(2) { 
            ["button1"]=> string(8) "Press me" 
            ["button2"]=> string(9) "Tickle me"
        }
    }
}

So I implemented this recursive function:

function clear_empty_array_values($array){
    foreach($array as $key => $value){
        if (is_array($value)){
            clear_empty_array_values($value);  
        }else{
            if (empty($value)){
                unset($array[$key]);
            }  
        }
    }
}

But when I call this function on my array:

clear_empty_array_values($my_array);

I get the same result as before calling the method.

Can you see what is wrong?

2 Answers 2

1

To modify $my_array in place as you show, you need to pass-by-reference &. Then to modify $value in the foreach use a reference &:

function clear_empty_array_values(&$array){
    foreach($array as $key => &$value){
        if (is_array($value)){
            clear_empty_array_values($value);
        }
        if(empty($value)) {
            unset($array[$key]);
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Added & to both the $array parameter and the $value variable, but it still shows the same for me, maybe is the array I send in that is wrong, updated my post with the actual data it gets. Sorry for the edit!
Ok now it works! Needed to remove the else so it removed empty arrays as well
OK, the logic looked sound but it would not remove the top-most array if empty. Edited.
1

Do this one: function clear_empty_array_values(&$array)

or, you must return value:

function clear_empty_array_values($array){
    foreach($array as $key => $value){
        if (is_array($value)){
            $array[$key] = clear_empty_array_values($value);  
        }else{
            if (empty($value)){
                unset($array[$key]);
            }  
        }
    }
return $array;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.