nGetIt Com - 7 months ago 48

PHP Question

Working with PHP.

I have array 1 with this keys and values:

`$array_1 = array(`

(more values)

'propub_cost_max' => 5,

'propub_cost_min' => 0.5,

'average_calc_last' => '-1 Months',

'propub_qtd_first_offer' => 4

);

and array 2:

`$array_2 = array(`

'propub_cost_max' => 20,

'propub_cost_min' => (no value),

'average_calc_last' => (no value),

'propub_qtd_first_offer' => (no value)

);

I want to merge array 2 with array 1 so i did:

`$result = array_merge($array_2, $array_1);`

But the result is:

`$result = array(`

(more values)

'propub_cost_max' => 5,

'propub_cost_min' => 0.5,

'average_calc_last' => '-1 Months',

'propub_qtd_first_offer' => 4

);

The propub_cost_max key should assume the value 20, right?

The idea is to maintain some values, and replace where the values are different if there is any value, of course.

I thought that array_merge should work, but...

Thank you all.

Answer

"If the input arrays have the same string keys, then the later value for that key will overwrite the previous one.". in your case array_1 is the latter.

Says nogad.

(link to `array_merge`

)

And also

You have a } instead of a parenthesis.

As says TheValyreanGroup.

Both of these are absolutely correct. So

```
$result = array_merge($array_1, $array_2);
```

Will solve your problem. Values are swapped so that `$array_2`

will now overwrite the values in `$array_1`

.

To solve your overall issue of wanting to update *some* values, without knowing which values and which conditions you want to preserve, we're reduced to simply not overwriting values with empty ones, so :

```
$array_2 = array_filter($array_2); //clears empty values
$result = array_merge($array_1, $array_2); // as before. updates non-empty new values.
```

Source (Stackoverflow)