0

I have two arrays with the same keys but different values. I need to merge it but if the values are the same leave only one of this

$array1 = array('firstname'=> $may_name, 'lastname'=>$my_last_name, 'address'=>$addres_1);

$array2 = array('firstname'=> $may_name, 'lastname'=>$my_last_name, 'address'=>$addres_2);

I need to get:

$array_result = array('firstname'=> $may_name, 'lastname'=>$my_last_name, 'address'=>$addres_1, 'address'=>$addres_2);

can anybody help to solve this? array_merge does not work for me..

2
  • Have you seen array_merge? Commented Feb 15, 2018 at 11:24
  • You can not have two identical keys at the same level Commented Feb 15, 2018 at 11:32

1 Answer 1

1

First you need to merge 2 arrays, using array_merge() function. then get the unique elements from the array using array_unique() function will get you the result

var_dump(array_unique(array_merge($array1, $array2)));

Edit

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. php doc

Thanks @Marco

Sign up to request clarification or add additional context in comments.

2 Comments

array_unique isn't needed actually. array_merge already does the job.
in my case array_merge does not job. I can't get what I need... Or I do something wrong...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.