tags:

views:

72

answers:

5

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.

+4  A: 

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

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

a.aman
Switch is shorter? With all those break statements?
James
+1  A: 

Hey,

looking at your example you could do something like

$id = strtolower($country) + '_type';
sTodorov
+6  A: 

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';
}
Mike
+1 Just what I was about to answer as well!
Jacob Relkin
Looks perfect, thanks man!
Happy
+1  A: 

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;
NAVEED
it seems to be too massive.
Happy
+1  A: 

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';