0

My goal is to take the language file according to the existence of the variable's value in the array and substitute with English in case it is not. Here is the code I wrote from scratch:

if(strpos($trns, $lng) === FALSE) {$trn = 'en';} else {$trn = $lng;}
include_once $trn.'.php';

where $trns is the array with language prefixes of existing translation files, $lng is the variable which holds the prefix that should be used in case it exists in the array and $trn is the selected prefix.

In my opinion in the human language this code reads like in case $lng is fr but there is no fr in the array then use en for $trn. Otherwise use fr.

Print_r($trns) output is Array ( [0] => en [1] => de ).

So the above code successfully uses the en.php file in case there is en in the array and $lng = en, the same for de.

But it also uses fr in spite of the fact there is no fr in the array, while it should substitute fr with en in such case.

I need your help in tracking the error I've made.

1 Answer 1

1

strpos does not work with arrays. Use in_array function.

if (!in_array($lng, $trns)) {
    $trn = 'en';
} else {
    $trn = $lng;
}
include_once $trn.'.php';

or shorter

$trn = in_array($lng, $trns) ? $lng: 'en';
include_once $trn.'.php';
Sign up to request clarification or add additional context in comments.

2 Comments

It works, thanks a lot! Marked as the answer. But what was the mistake I've made in my code?
strpos does not look into arrays but in strings.

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.