Julien
Julien

Reputation: 4163

simplify massive same php conditions

I have a question, I wonder what is the best way to print many different strings depending a language, I mean, today I have sthg simple :

function getStringA($lang,$data1,$data2){
   if($lang=='en'){return 'my string is '.$data1.' and '.$data2;}
   elseif($lang=='fr'){return 'ma chaine est '.$data1.' et '.$data2;}
   elseif($lang=='it'){return $data1.'blabla '.$data2.' blabla';}
   ..
   [50 conditions]
}

function getStringB($lang,$data){
    [same 50 conditions, one per language]
}

function getStringC($lang,$data){
  ..
}
...

and then :

echo getStringA('en','test','test1');
echo getStringB('en','AAAA');
echo getStringB('en','BBBB');
..
  1. there is always those same 50 languages conditions on each function
  2. the place of data parameters can change in the string (at the end, middle..)

I thought to use printf but I don't know if it will be really better, I need sthg fast and most important, easy to maintain.

Any idea ?

Upvotes: 1

Views: 52

Answers (3)

Robert
Robert

Reputation: 20286

Use arrays and to pass params you can use vsprintf() function

$translate = [
  'en' => [
     'my_string_is' => 'my string is %s and %s';
  ],
  'fr' => [
     'my_string_is' => 'ma chaine est %s et %s';
  ]
];

function translate ($translations, $word, $lang, array $params = []) {
   return isset($translations[$lang][$word]) ? vsprintf($translations[$lang][$word], $params) : $word;
}

// usage

echo translate($translations, 'my_string_is' ,'en', ['wordA', 'wordB']);
echo translate($translations, 'my_string_is' ,'fr', ['wordA', 'wordB']);

This is very basic idea. It can be written better. Translation can be held in config files like ini, xml, yaml etc also it could be written in OOP so it would be better to use.

Upvotes: -1

marian0
marian0

Reputation: 3337

Put your strings into array and change concatenation into printf()-alike function format:

$stringsA = array(
    'en' => 'my string is %s and %s',
    'fr' => 'ma chaine est %s et %s',
    // ...
);

Then in your function get text by array key:

function getStringA($lang,$data1,$data2){
    return isset($stringsA[$lang])? vprintf($stringsA[$lang], array($data1, $data2)) : '';
}

You can also use your own placeholders in strings and str_replace() function:

// e.g. 'my string is {propery} and {secondProperty}'


function getStringA($lang,$data1,$data2){
    return isset($stringsA[$lang])? str_replace(array('{propery}', '{secondProperty}'), array($data1, $data2), $stringsA[$lang]) : '';
}

Upvotes: 2

Marc B
Marc B

Reputation: 360762

Why not an array?

$conditions = ['en' => 'foo', 'fr' => 'bar', etc...]

if (isset($conditions[$lang])) {
   return $conditions[$lang];
} else {
   return $default_value;
}

Upvotes: 0

Related Questions