I have two arrays:
Array
(
[2005] => 0
[2006] => 0
[2007] => 0
[2008] => 0
[2009] => 0
)
Array
(
[2007] => 5
[2008] => 6.05
[2009] => 7
)
I want to merge these two arrays such that if a value exists in the 2nd array, it overwrites the first array's value. So the resulting array would be:
Array
(
[2005] => 0
[2006] => 0
[2007] => 5
[2008] => 6.05
[2009] => 7
)
Thanks for your help.
UPDATE: This was my best attempt, but it's wildly unsuccessful:
$final = '';
foreach ($years as $k => $v){
if (in_array($k,$values)){
$final .= $values[$k] . '|';
}else{
$final .= $k[$v] . '|';
}
}
echo "final = $final";
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.
You can use the PHP array_unique() function and PHP array_merge() function together to merge two arrays into one array without duplicate values in PHP.
1. array_combine(): It is used to creates a new array by using the key of one array as keys and using the value of another array as values. 2. array_merge(): It merges one or more than one array such that the value of one array appended at the end of the first array.
As I've just recently learned, PHP has an array union operator that does exactly this:
$result = $a + $b;
Where $a is the array with the values that you want to take precedence. (So in your example, that means that the second array is "$a
".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With