I am developing a simple landing page where you can choose the language of the text displayed.
This is my code:
<?php
$defaultLang = isset($_COOKIE['lang_bcn']) ? $_COOKIE['lang_bcn'] : 'es'; //default
if(isset($_GET['selectedLanguage'])){
$languageOption = "";
switch($_GET['selectedLanguage']){
case 'en':
$languageOption = 'en';
break;
case 'es':
$languageOption = 'es';
break;
default:
break;
}
if(isset($languageOption)){
setcookie('lang_bcn',$languageOption,time() 24*7*60*60);//set cookie to expire in 7 days
}
}
$arrayLang['en']['subtitle'] = 'Discover and learn by playing';
$arrayLang['es']['subtitle'] = 'Descubre y aprende jugando';
?>
//links to language selection
<a href="?selectedLanguage=es">ES</a>
<a href="?selectedLanguage=en">EN</a>
//showing the text in the selected language
<p><?php echo $arrayLang[$defaultLang]['subtitle'];?></p>
And it works great, except that to change the language I have to click twice on the chosen language link. With just one click the language of the text doesn't change and I can't find the reason why.
Can someone help me?
Thank you!
CodePudding user response:
Your $defaultLang
variable is defined on the top and it depends on the cookies. When you click your button the first time, the cookies aren't set yet, so $defaultLang
is going to be 'es'
and after that you set the cookies. The second time you click your button cookies are already set, so $defaultLang
variable is set to proper value. Just put it below if
statement and it should work.
if(isset($_GET['selectedLanguage'])){
$languageOption = "";
switch($_GET['selectedLanguage']){
case 'en':
$languageOption = 'en';
break;
case 'es':
$languageOption = 'es';
break;
default:
break;
}
if(isset($languageOption)){
setcookie('lang_bcn',$languageOption,time() 24*7*60*60);//set cookie to expire in 7 days
}
}
$defaultLang = isset($_COOKIE['lang_bcn']) ? $_COOKIE['lang_bcn'] : 'es'; //default