YKKY
YKKY

Reputation: 605

Choose PHP variable's value depending on array content

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.

Upvotes: 0

Views: 33

Answers (1)

Stefanov.sm
Stefanov.sm

Reputation: 13049

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';

Upvotes: 1

Related Questions