Oké. I saw this piece of code and I was curious about how it works and what it does. Can anyone explain this to me? Thanks!
$_SESSION['langtype']
= (empty($_SESSION['langtype'])) ? 'false' : $_SESSION['langtype'];
Oké. I saw this piece of code and I was curious about how it works and what it does. Can anyone explain this to me? Thanks!
$_SESSION['langtype']
= (empty($_SESSION['langtype'])) ? 'false' : $_SESSION['langtype'];
It puts false in $_SESSION['langtype']
is the value is not set, otherwise it keeps the current value.
See also http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
It puts "false"
in $_SESSION['langtype']
(as a STRING, not BOOL VALUE) in case $_SESSION['langtype']
is empty (or value with key langtype
does not exist), otherwise keeps the same value.
It's probably bad idea to put "false"
as a string. For example if the author of this masterpiece decides to do a check if ($_SESSION['langtype']) { }
, it will return true in any case. I'm curious in which case this solution should be reasonable.
Its a short hand for if-else
statement. if (empty($_SESSION['langtype']))
then $_SESSION['langtype'] = false
else $_SESSION['langtype'] = $_SESSION['langtype']
This is ternary Operator used in this Statement
$_SESSION['langtype'] = (empty($_SESSION['langtype'])) ? 'false' : $_SESSION['langtype'];
It means If Session variable named langtype is empty then return false, Otherwise use langtype same as defined
The portion after ? represent the value if function
empty($_SESSION['langtype'])returns true(Mean if it is empty then set it false or un-define that variable) i.e
$_SESSION['langtype'] = false;
and portion after : represent else statement that is if langtype is not empty then keep it as it is(Equal to Defined Value) as
$_SESSION['langtype']=$_SESSION['langtype'];
It is called a ternary operator. it consists of condition expression, and return values for both evaluations of the condition.
// if expression evaluates to true first value will be returned,
// otherwise it will the second
$variable = (expression) ? 'value if true' : 'value if false';
if it is not set(true) then it will be false else if its (false) it ill print the session value
$_SESSION['langtype'] = (empty($_SESSION['langtype'])) ? 'false' : $_SESSION['langtype'];
For a beginner the above code is the same as the long version which you might know
<?php
if(empty($_SESSION['langtype'])) {
$_SESSION['langtype'] = 'false';
} else {
$_SESSION['langtype'] = $_SESSION['langtype'];
}
?>