How to simplify this php switch statement?

I would like to change this:

// use appropiate lang.xx.php file according to the value of the $lang switch ($_SESSION['lang']) { case 'en': $lang_file = 'lang.en.php'; break; case 'es': $lang_file = 'lang.es.php'; break; case 'zh-tw': $lang_file = 'lang.zh-tw.php'; break; case 'zh-cn': $lang_file = 'lang.zh-cn.php'; break; default: $lang_file = 'lang.en.php'; } 

into something like this:

 //include file for final output include_once 'languages/lang.'.$_SESSION['lang'].'php; 

(I think the $lang_file variable becomes redundant if I do the included output-output-output above)

So that I can skip the entire switch part. I tried other combinations, but they don't seem to work. Any suggestions?

+4
source share
4 answers

You can do it:

 switch ($_SESSION['lang']) { case 'en': case 'es': case 'zh-tw': case 'zh-cn': $lang_file = 'lang.'.$_SESSION['lang'].'.php'; break; default: $lang_file = 'lang.en.php'; } 

Or you use an array and use in_array to find out if the value is in the array:

 $languages = array('en', 'es', 'zh-tw', 'zh-cn'); if (in_array($_SESSION['lang'], $languages)) { $lang_file = 'lang.'.$_SESSION['lang'].'.php'; } else { $lang_file = 'lang.en.php'; } 

You can even omit en in both cases, since it is the default.

+17
source
 $lang_file = 'lang.' . ($_SESSION['lang']) . 'php'; if(!file_exists($lang_file)) { $lang_file = 'lang.en.php'; } 

although it is not protected against injections. However, it allows you to add new language codes without changing the code.

+2
source

Or:

 $allowed = array('en', 'es', 'zh-tw', 'zh-cn'); $lang_file = (in_array($_SESSION['lang'], $allowed)) ? 'lang.'.$_SESSION['lang'].'.php' : 'lang.en.php'; 
+2
source

It will work great

 $lang_file_tmp = 'lang.' . $_SESSION['lang'] . '.php'; if ( preg_match( '/^[a-zA-Z\-]{2,5}$/', $_SERSSION['lang'] ) && file_exists( $lang_file_tmp ) ) { $lang_file = $lang_file_tmp; } else { $lang_file = 'lang.en.php'; } 

In this case, you do not have to edit the code every time you add a new language, and you do not have to worry about security.

0
source

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


All Articles