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.

2
  • 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 Commented Nov 14, 2013 at 19:08
  • your right, not sure what I was thinking. Commented Nov 14, 2013 at 19:19

2 Answers 2

3

You need to use array_key_exists instead of in_array

2
  • Note the isset vs array_key_exists however, stackoverflow.com/questions/3210935/… Commented Nov 14, 2013 at 19:11
  • Doh your right, that was the problem, thanks for refreshing my memory. Commented Nov 14, 2013 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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.