0

I'm rebuilding the language system on my php application to make it easier to create translations.

one of the things I did was convert everything to one big array $lang; here is an example of what that looks like:

$lang['common:login'] = "Login";
$lang['common:signup'] = "Sign Up";
$lang['index:title'] = "Home Page";
$lang['messages:newmessages'] = "You have %s new messages";

I load it by using the following code:

require_once "lang/en/lang.php";

calling $lang['common:login'] will wqork with no problem, the problems occurred once I made a function for loading these compared to the other way I've done it in the past.

function outputLanguage($tag) {

    global $lang;

    //see if tag exists.
    if (!in_array($tag, $lang)) {
       return $tag." is an invalid language tag.";
    }  else {
       return $lang[$tag];
    }
}

it seems that in_array() doesn't like to work with arrays that included from another source.

I honestly would like to have some validation in case someone made a mistake, so does anyone know of a good solution?

Thanks.

Eman
  • 1,093
  • 2
  • 26
  • 49
  • 1
    in_array() doesn't know or care that the $lang array was included from another source; but surely you should be testing for the key, not the value... and in_array() tests for values – Mark Baker Nov 14 '13 at 19:08
  • your right, not sure what I was thinking. – Eman Nov 14 '13 at 19:19

2 Answers2

3

You need to use array_key_exists instead of in_array

Tesserex
  • 17,166
  • 5
  • 66
  • 106
  • Note the `isset` vs `array_key_exists` however, http://stackoverflow.com/questions/3210935/difference-between-isset-and-array-key-exists – hank Nov 14 '13 at 19:11
  • Doh your right, that was the problem, thanks for refreshing my memory. – Eman Nov 14 '13 at 19:18
0

You are looking for the array key, try:

if(!isset($lang[$tag])) {
    return $tag." is an invalid language tag.";
} else {
    return $lang[$tag];
}

Or I would return false:

return isset($lang[$tag]) ? $lang[$tag] : false;
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87