-1

i have a foreach where i want to compare some strings from two arrays

output of variable $count_land

Array
(
    ["US"] => 186
    ["DE"] => 44
    ["BR"] => 15
    ["FR"] => 3
    ["other"] => 7
)

Other array:

 $all_lands_array = ["CN", "DE", "US", "EU", "RU", "BR", "GB", "NL", "LU", "other", "IT"];

what i need is every key in the $all_lands_array that have the same letters from the $count_land array and save them in another variable

that means i need to get US, DE, BR, FR, other and save them in a new variable

i hope you understand what i need :)

this is my loop but it doesnt find any match.. but why?

foreach($all_lands_array as $lands){
    if($lands == $count_land)
        return "match";
    else
        return "no match!";
    }
PHPprogrammer42
  • 355
  • 1
  • 3
  • 7

2 Answers2

1

You have to save the countries in a variable as an array and use in_array to check if an element is in that array:

    $found = array();
    $countries = array_keys($count_land); //stores: US,DE..etc
    foreach($all_lands_array as $country){
        if(in_array($country, $countries)){ //if a country name is found in $countries array, 
           //OPTIONALLY: exclude 'other'
            //if(in_array($country, $countries) && $country !='other')
            $found[] = $country; //store them in the $found variable
        }
    }

Test

$count_land = array('US'=>1,'DE'=>1,'BR'=>1,'FR'=>1,'other'=>1);
$all_lands_array = ["CN", "DE", "US", "EU", "RU", "BR", "GB", "NL", "LU", "other", "IT"];

var_dump($found);
array(4) {
  [0]=>
  string(2) "DE"
  [1]=>
  string(2) "US"
  [2]=>
  string(2) "BR"
  [3]=>
  string(5) "other"
}
ka_lin
  • 9,329
  • 6
  • 35
  • 56
1

Because you just loop through one array and then check the value against the whole other array.

Checking for country codes:

$count_land = array
(
    "US" => 186,
    "DE" => 44,
    "BR" => 15,
    "FR" => 3,
    "other" => 7
);

$all_lands_array = array("CN", "DE", "US", "EU", "RU", "BR", "GB", "NL", "LU", "other", "IT");

$matches = array();   


foreach($count_land as $key => $val){
        if(in_array($key, $all_lands_array)){
            $matches[$key] = $val; // add matches to array;
        }else{
           // do nothing
        }
    }

print_r($matches);die;

returns:

Array ( [US] => 186 [DE] => 44 [BR] => 15 [other] => 7 )

Dennis Heiden
  • 757
  • 8
  • 16