0
\$\begingroup\$

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

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

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

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

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

array:13 [
  "Ontario" => 1
  "Manitoba" => 0
  "New Brunswick" => 0
  "Yukon" => 0
  "Saskatchewan" => 0
  "Prince Edward Island" => 0
  "Alberta" => 17
  "Quebec" => 0
  "Nova Scotia" => 0
  "British Columbia" => 0
  "Nunavut" => 0
  "Newfoundland and Labrador" => 0
  "Northwest Territories" => 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 => $value_x) {

    foreach ($country_states as $state_y => &$value_y) {

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

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

            $value_y = 0;
        }
    }
}
New contributor
ibrahim.fathy is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$

Your Answer

ibrahim.fathy is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.