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' => []
];

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

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