How can I use php loop inside if else statement

if (isset($_GET['language']) && !empty($_GET['language'] && $_SESSION['language'] !== $_GET['language'])) {
if ($_GET['language'] === 'en') {
$_SESSION['language'] = 'en';
} elseif ($_GET['language'] === 'ar') {
$_SESSION['language'] = 'ar';
} elseif ($_GET['language'] === 'de') {
$_SESSION['language'] = 'de';
} else {
$_SESSION['language'] = $default_language;
}
}
I would like to loop only elseif statements. Is there away to achieve this?
Answer
Solution:
There's no need for a loop here. If your intention is to whitelist the available languages then put a list in an array and usein_array()
:
$languages = ['ar','de','en'];
if (isset($_GET['language']) && in_array($_GET['language'], $languages)) {
$_SESSION['language'] = $_GET['language'];
} else {
$_SESSION['language'] = $default_language;
}
Answer
Solution:
You don't need to doisset
andempty
asempty
will do that for you.
This also checks if the language is in one of the specific ones (usingin_array
) and if it isn't then it uses the default...
if (!empty($_GET['language']) && $_SESSION['language'] !== $_GET['language']) {
$_SESSION['language'] = in_array($_GET['language'], ['en', 'ar', 'de'])
? $_GET['language'] : $default_language;
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: attempt to read property "id" on null
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.