How to put multiple variable in a language file of Codeigniter How to put multiple variable in a language file of Codeigniter codeigniter codeigniter

How to put multiple variable in a language file of Codeigniter


Try something like this using vsprintf():

// Method 1: pass an arrayfunction my_lang($line, $args = array()){  $CI =& get_instance();  $lang = $CI->lang->line($line);  // $lang = '%s %s were %s';// this would be the language line  return vsprintf($lang, $args);}// Outputs "3 users were deleted"echo my_lang('users.delete_user', array(3, 'users', 'deleted'));// Method 2: read the argumentsfunction my_lang2(){  $CI =& get_instance();  $args = func_get_args();  $line = array_shift($args);  $lang = $CI->lang->line($line);  //  $lang = '%s %s were %s';// this would be the language line  return vsprintf($lang, $args);}// Outputs "3 users were deleted"echo my_lang2('users.delete_user', 3, 'users', 'deleted');

Use the first argument of the function to pass the line index, get the correct line from CI, and pass an array as the second param (method1) or the rest of the arguments as each variable (method2). See the docs on sprintf() for formatting: http://www.php.net/manual/en/function.sprintf.php

CI's native lang() function uses the second param to pass an HTML form element id and will create a <label> tag instead - not a great use of this function if you ask me. If you don't use the label feature, it might be a good idea to create a my_language_helper.php and overwrite the lang() function to do this stuff natively, instead of writing a new function.

Here is what my actual lang() function looks like, I don't need the <label> option so I overwrote the second param to accept a string or an array of variables instead:

// application/helpers/my_language_helper.phpfunction lang($line, $vars = array()){    $CI =& get_instance();    $line = $CI->lang->line($line);    if ($vars)    {        $line = vsprintf($line, (array) $vars);    }    return $line;}

Such an small, easy change for this benefit, I wish it were the default - I never use lang() to output a <label> tag, but need to pass variables to it frequently.