Alberto Alberto - 5 months ago 26
PHP Question

PHP Compare keys and change certain values from a multidimensional array with corresponding keys' values from a simple array

I have two arrays (one simple and one multidimensional) and I want to verify if certain keys from the multidimensional array have empty values and replace them with their correspondent values from the simple array.

Solution for both simple arrays and/or 2D arrays is here:

PHP Compare and change certain elements in multidimensional arrays

But what would be the solution in the situation above?

Example of simple array:

$superheroes_complete = array(
1 => 'one',
'two' => 'two',
3 => 'three',
'email' => 'peterparker@mail.com',
5 => 'cinco',
6 => 'six',
'name' => 'Clark Kent',
8 => 'eight'
);


Example of multidimensional array:

$superheroes_empty = array(
"spiderman" => array(
"name" => "Peter Parker",
"email" => "",
),
"superman" => array(
"name" => "",
"email" => "clarkkent@mail.com",
),
"ironman" => array(
"name" => "Harry Potter",
"email" => "harrypotter@mail.com",
)
);


Expectation:

$superheroes_empty = array(
"spiderman" => array(
"name" => "Peter Parker",
"email" => "peterparker@mail.com",
),
"superman" => array(
"name" => "Clark Kent",
"email" => "clarkkent@mail.com",
),
"ironman" => array(
"name" => "Harry Potter",
"email" => "harrypotter@mail.com",
)
);


Thank you in advance.

Answer

Here is one way to do this using array_walk_recursive:

array_walk_recursive($superheroes_empty, function(&$v, $k) use ($superheroes_complete) {
    if ($v === '' && isset($superheroes_complete[$k])) {
        $v = $superheroes_complete[$k];
    }
});

This will fill in any empty values if a corresponding key is found in $superheroes_complete. Since this makes replacements by reference, it will directly change the $superheroes_empty array, so if you still need the one with empty values, make a copy before using this.