1

I have two arrays with different length, but keys are similar.
My requirement is update $array1 with values of $array2 similar keys

$array1 = array("Jan"=>"0", "Feb"=>"0", "Mar"=>"0", "Apr"=>"0");

$array2 = array("Jan"=>"2", "Mar"=>"3");

Output:

$res = array("Jan"=>"2","Feb"=>"0","Mar"=>"3","Apr"=>"0");
1
  • try $array2+$array1 Commented Dec 23, 2015 at 5:19

3 Answers 3

11

You can achieve it by this code:

$array1 = array("Jan" => "0", "Feb" => "0", "Mar" => "0", "Apr" => "0");

$array2 = array("Jan" => "2", "Mar" => "3");

$array3 = array_replace($array1, $array2);
print_r($array3);
Sign up to request clarification or add additional context in comments.

2 Comments

You can use existing $array1 instead of $array3, if you don't want to create new array.
Thank you very much Mr.Maha Dev
0

You can simply use + operator.

$array1 = array("Jan"=>"0","Feb"=>"0","Mar"=>"0","Apr"=>"0");
$array2 = array("Jan"=>"2", "Mar"=>"3");
print_r($array2 + $array1);

DEMO

Comments

0

Try this:

array_merge($array1, $array2);

3 Comments

output from your code is Array ( [Jan] => 2 [Feb] => 0 [Mar] => 3 ) can you explain why array_unique?
but the output should be $res = array("Jan"=>"2","Feb"=>"0","Mar"="3","Apr"=>"0"); as per question
array_unique will remove all duplicate elements having same value. 0 in this case for Feb and Apr.

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.