DEV Community

Adrián Vera
Adrián Vera

Posted on • Edited on

2 1

Replace recursively only empty array values

Hey fellow coders, i need your assistance! (please send help)

lets say i got array A and array B:

A = [
'personal_data' => [ A => ['test' => A]],
'family_data' => [ A => ['test' => A]],
];

B = [
'personal_data' => '',
'family_data' => [ B => ['test' => B]],
'payment_info' => []
];

i got to replace the data from array A with array B having a preference over array A. (need to replace A with B:
if keys don't exist add them
if key exists and value differs replace value
if key exists and value does not differ do nothing)

i.e:

A = [
'personal_data' => '',
'family_data' => [
A => ['test' => A]
B => ['test' => B]
],
'payment_info' => []
];

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (2)

Collapse
 
kushal-niroula profile image
Kushal Niroula

From what you describe, shouldn't the resulting array have personal_data as empty string, as the second array would overwrite it?

Collapse
 
medadrian profile image
Adrián Vera • Edited

Yes, you are right, i already commented on the problem

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay