I'd like to merge these two arrays based on their key, and only keep the key matches. The merged array should retain the key, and the value should come from the second array.
Array #1: States I've Visited
Array
(
[AL] => 113
[AZ] => 83
[CA] => 50
[CO] => 1
...
Array #2: All States
Array
(
[AL] => ALABAMA
[AK] => ALASKA
[AZ] => ARIZONA
[AR] => ARKANSAS
[CA] => CALIFORNIA
[CO] => COLORADO
[CT] => CONNECTICUT
...
So, If I've been to a state, I'd like to get the name of that state from Array 2. And throw out any non-matching nodes from array #2.
Desired Result
Array
(
[AL] => ALABAMA
[AZ] => ARIZONA
[CA] => CALIFORNIA
[CO] => COLORADO
...
I've done extensive research in the PHP manual and on StackOverflow, and cannot find a particular answer to this. I think it probably lies in a more complex user defined function than I am capable of at this point.
array_merge()
almost does what I want, but then it adds the states I have not visited to the end of the array
array_intersect_key()
also gets close. It keeps only the matching keys, but then it gets rid of values.
Enjoy this mildly inefficient example while I write a better solution. http://codepad.org/hIjPEM81
Inefficient Solution 1:
<?php
$allstates=array("MO"=>"Missouri", "TX"=>"Texas");
$statesIveBeenTo = array("MO"=>1);
foreach($allstates as $k=>$v){
if(!array_key_exists($k,$statesIveBeenTo)){
unset($allstates[$k]);
}
}
var_dump($allstates);
Outputs:
array(1) {
["MO"]=>
string(8) "Missouri"
}
Solution 2:
$test = array_intersect_key($allstates, $statesIveBeenTo);
var_dump($test);
The same output as above.