Php if else

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

And a variable $id.

We need to give a value $idcorresponding to the value $country, for example:

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

else if repeated every time, and other data is typical.

Is there any way to make this code shorter?

how

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

Thank.

+3
source share
5 answers

You can simply create $idfrom $country:

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

If you first need to determine validity $country, put all of your countries in an array, and then use in_arrayto determine if $country:

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

Use a management structure switch. This will make your code shorter.

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

+4

, -

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

:

$countries = array( "0" => array("country_name" => "usa", 
                                 "country_type" => "001" ) ,

                    "1" => array("country_name" => "uae", 
                                 "country_type" => "002" ),

                    -----------------------------
                    -----------------------------

                  );

, , .

$country = "usa";

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

echo $id;
+1

or you can 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';
+1
source

Source: https://habr.com/ru/post/1757527/


All Articles