Jump to content

Checking an array for multiple kinds of values...


bluegray

Recommended Posts

Forgive my brevity, I'm short on time, and don't exactly know how to articulate this question.

 

So I'm going to have an array with different country names in it.  Call it $country []. 

 

Now I need to check the array for any non-U.S. country.  The array will always have at least 1 U.S. in it, but I need to know how to check for true/false the presence of there also being something else like UK, MX, AU, etc. 

 

Do I need to specify anything else?  Please help me, PHP addicts  :confused:.

 

What is the structure of the array you have? Can you post some sample data, or perhaps a print_r() of it?

 

Okay, so here's my goal.  I need to make sure a foreign country portion of the page is not displaying if there are no foreign countries (native country being U.S.) in the array.

 

here's an example of the $country array on a dump:

array(4) { 
[0]=>  string(2) "US" 
[1]=>  string(2) "US" 
[2]=>  string(2) "US"  
} 

 

So naturally I don't want the "Foreign" country section to display if there are no foreign countries.  However, there are alternatively some 40+ other country names to check for so I need a solution that scans for anything that's not the U.S. and then returns a true/false. 

 

Try this. If $non_us == TRUE, that means there are other countries in the array. Do these values come from a database query, by chance?

 

$non_us = '';
foreach( $array as $v ) {
     if( $v != 'US' ) {
          $non_us = TRUE
          break;
     }
}

Ah okay, I slightly misunderstood, I thought it was the other way around, checking if 'US' was in array.

 

I like the array_unique solution. Here's another one-liner:

if (count(array_diff($countries,array('US'))) > 0) {
  // non-US in array
}

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.