Rencontres Intenses
Rencontres Intenses

Reputation: 33

PHP: recursively empty multidimensional array

Let's take the following multidimensional array example:

$table=array(
"phone"=>array("value"=>"value 1", "message"=>"message 1"),
"email"=>array("value"=>"value 2", "message"=>"message 2"),
"passwd"=>array("value"=>"value 3", "message"=>"message 3")
);

print_r will display:

Array ( [phone] => Array ( [value] => value 1 [message] => message 1 ) [email] => Array ( [value] => value 2 [message] => message 2 ) [passwd] => Array ( [value] => value 3 [message] => message 3 ) ) 

I need a function that will empty all the "value" and "message" keys, so that print_r will now display:

Array ( [phone] => Array ( [value] => [message] => ) [email] => Array ( [value] => [message] => ) [passwd] => Array ( [value] => [message] => ) )

I tried with the following:

function recursively_erase($table){
    foreach($table as $row=>$array)
        foreach($array as $key=>$value)
            $value="";
}

But it's not working. Has someone a better idea ?

Thanks

Upvotes: 3

Views: 105

Answers (2)

q.Then
q.Then

Reputation: 2751

Recursive solution to empty out any multidimensional array at any level

If you want to do a recursive solution to empty out a multidimensional array:

$array = array(
'hi' => array(1, 2, 3),
'bye' => array(
    'exe' => array(1, 2, 3, 4)
)
);
    function recursive_empty($input) {
        if (is_array($input)) {
            //Check to see if array is associative, else just return blank array
            if ((bool)count(array_filter(array_keys($input), 'is_string'))) {
                foreach ($input as $key=>$val) {
                    $input[$key] = recursive_empty($val);
                }
            }
            else {
                return array();
            } 
        }
        return $input;
    }
print_r(recursive_empty($array));

For any value in any array at any level, if there is an associated array to the key, it will empty it. This works for any depth such as:

array(
'hi' => array(),
'bye' => array(
    1 => array(1, 2, 3)
)

Upvotes: 0

Marc B
Marc B

Reputation: 360772

foreach makes COPIES of array contents, so you're modifying those copies, which then get throw away on the next iteration.

Try

foreach($table as $row=>$array) {
   foreach($array as $key=>$value) {
       $table[$row][$key] = "";
       ^^^^^^^^^^^^^^^^^^
   }
}

so you're modifying the original top-level array, and not the disposable child arrays/values.

Upvotes: 1

Related Questions