3

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.

1
  • Why is this important? Sometimes having longer code is worth the trade off if the shorter code is harder to understand and is so complex there is the potential for bugs to creep in. Commented Aug 1, 2010 at 9:03

5 Answers 5

6

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';
}
Sign up to request clarification or add additional context in comments.

Comments

4

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

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

1 Comment

Switch is shorter? With all those break statements?
1

looking at your example you could do something like

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

Comments

1

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;

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.