Tutorial :PHP if else statements



Question:

We have variable $country, it can give ~50 different values.

And variable $id.

What we should do is to give a value for $id corresponding to $country value, like:

if ($country = 'USA') { $id = 'usa_type'; }  else if ($country = 'France') { $id = 'france_type'; }  else if ($country = 'German') { $id = 'german_type'; }  else if ($country = 'Spain') { $id = 'spain_type'; }  ...  ...  ...  else if ($country = 'Urugway') { $id = 'urugway_type'; }  else { $id = 'undefined'; }  

else if statement repeats everytime, and other data is typical.

Is there a way to make this code shorter?

Like:

[france]:'france_type;  [england]:'england_type;  ...  [else]:'undefined'  

Thanks.


Solution:1

You could just create $id from $country:

$id = strtolower($country) . '_type';  

If you first need to determine the validity of $country, put all your countries in an array, then use in_array to determine if $country is valid:

$countries = array('USA', 'France', 'Germany', 'Spain', 'Uruguay');  if (in_array($country, $countries)) {      $id = strtolower($country) . '_type';  }  


Solution:2

Use switch control structure . It will make your code shorter.

http://php.net/manual/en/control-structures.switch.php


Solution:3

looking at your example you could do something like

$id = strtolower($country) + '_type';  


Solution:4

Place all countries and codes in array like this:

$countries = array( "0" => array("country_name" => "usa",                                    "country_type" => "001" ) ,                        "1" => array("country_name" => "uae",                                    "country_type" => "002" ),                        -----------------------------                      -----------------------------                      );  

Then use loop to compare country name and then get country id.

$country = "usa";    for( $i = 0; $i < count($countries); $i++ ) {     if( $country == $countries[$i]["country_name"] ){        $id = $countries[$i]["country_type"];        break;     }  }    echo $id;  


Solution:5

or you could create an array

$country_to_id = array(    "USA" => "usa_type",    "Spain" => "spain_type_or_whatever",    ....  );  $country_id = (array_key_exists($country,$country_to_id)) ? $country_to_id[$country] : 'undefined';  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »