phparraysunset

PHP: Unset All Empty Key Value Pairs of an Array


I have an associative array in my PHP code. I want to unset all the keys that have empty value. I know individual keys can be unset using the following code

unset($array_name['key_name']);

What I don't know is how to recursively do this with an array. While searching for an answer I came across answers recommending PHP built-in function array_filter(), however I failed to grasp how that works. So here's the code I tried to write but it doesn't work either.

<?php
function unset_all_empty_array_keys($associative_array){
    foreach ($associative_array as $key => $value){
        if ($value == ""){
            unset($associative_array['$key']); // This doesn't work.
        }
    }
};

$list = array(
    "item1" => "one",
    "item2" => "",
    "item3" => "three",
);
unset_all_empty_array_keys($list, '$list');
print_r($list);

echo "<br>";

// Manually Unsetting key-value pair works fine.
unset($list['item2']);
print_r($list);
?>

Solution

  • When you want do it with 'foreach()' then by reference:

    function unset_all_empty_array_keys(&$associative_array){
        foreach ($associative_array as $key => &$value){
            if ($value == ""){
                unset($associative_array[$key]);
            }
        }
    }
    

    The way with 'array_filter()':

    $list = array_filter($list,function($a){
        return $a!='';
    })
    

    And can only work 'recursively' on multi-dimensional array $a = ['a'=>['b'=>'']]; Your example is an flat array with only one dimension.

    So here the version for multi-dimensional arrays:

    $list = array(
        "item1" => "one",
        "item2" => "",
        "item3" => array(
            "item1" => "one",
            "item2" => "",
            "item3" => "three",
        )
    );
    
    
    function unset_all_empty_array_keys_recursive(&$associative_array){
        foreach ($associative_array as $key => &$value){
            if ($value == ""){
                unset($associative_array[$key]);
            } else if (is_array($value)){
                unset_all_empty_array_keys_recursive($value);
            }
        }
    }
    unset_all_empty_array_keys($list);
    var_export($list);