Map associative array to another array php I have an associative array of the states of some country, and the states names are the keys:

array:13 [
  "Ontario" =&gt; null
  "Manitoba" =&gt; null
  "New Brunswick" =&gt; null
  "Yukon" =&gt; null
  "Saskatchewan" =&gt; null
  "Prince Edward Island" =&gt; null
  "Alberta" =&gt; null
  "Quebec" =&gt; null
  "Nova Scotia" =&gt; null
  "British Columbia" =&gt; null
  "Nunavut" =&gt; null
  "Newfoundland and Labrador" =&gt; null
  "Northwest Territories" =&gt; null
] 


And I have anothe associative array that contains all states that have values:

array:8 [
  "Alberta" =&gt; 17
  "Cairo" =&gt; 1
  "Calgary" =&gt; 1
  "ddd" =&gt; 4
  "gfdxf" =&gt; 1
  "New Cairo" =&gt; 1
  "Ontario" =&gt; 1
  "secret" =&gt; 30
] 


Now I need to map the second array to the first one so that the result would be:

array:13 [
  "Ontario" =&gt; 1
  "Manitoba" =&gt; 0
  "New Brunswick" =&gt; 0
  "Yukon" =&gt; 0
  "Saskatchewan" =&gt; 0
  "Prince Edward Island" =&gt; 0
  "Alberta" =&gt; 17
  "Quebec" =&gt; 0
  "Nova Scotia" =&gt; 0
  "British Columbia" =&gt; 0
  "Nunavut" =&gt; 0
  "Newfoundland and Labrador" =&gt; 0
  "Northwest Territories" =&gt; 0
] 


I created a nested loop and it works fine, but the code is very ugly, now is there a more efficent way to do it?

My code:

foreach ($all_states as $state_x =&gt; $value_x) {

    foreach ($country_states as $state_y =&gt; &amp;$value_y) {

        if (strtolower($state_x) == strtolower($state_y)) {

            $value_y = $value_x;
        } elseif ($value_y == NULL) {

            $value_y = 0;
        }
    }
}
array_replace() is the perfect call here -- it can be used to overwrite the master array with the array containing actual integer values.

Code: (Demo)

var_export(array_replace(array_map('intval', $all_states), $country_states));


To streamline the process futher, you should declare your master list with 0 values instead of null values, then you can omit the array_map() call like this:

Code: (Demo)

var_export(array_replace($all_states, $country_states));


Additional suggestions, caveats, and considerations:


You might reconsider your variable names, as they don't seem to do a great job of describing the data that they contain.  $all_states might be $statesLookup or $statesDefault.  I don't know what is being counted in the second array, but $country_states might be better declared as $state_counts or something.
If $country_states has any elements with keys that are not represented in $all_states, then these new elements WILL be appended to the end of the output array.  If this is a legitimate concern, you can call array_intersect_key($country_states, $all_states) to filter out any expected elements.
The order of the elements in the output array will be ordered by $all_states.  No matter what order the country_states are in.