Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 888
Rencontres Intenses Avatar asked Nov 26 '25 06:11

Rencontres Intenses


1 Answers

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.

like image 117
Marc B Avatar answered Nov 28 '25 20:11

Marc B