Is there a way to define a php variable to be one or the other just like you would do var x = (y||z)
in javascript?
Get the size of the screen, current web page and browser window.
var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
i'm sending a post variable and i want to store it for a later use in a session. What i want to accomplish is to set $x
to the value of $_POST['x']
, if any exist, then check and use $_SESSION['x']
if it exist and leave $x
undefined if neither of them are set;
$x = ($_POST['x'] || $_SESSION['x');
According to http://php.net/manual/en/language.operators.logical.php
$a = 0 || 'avacado'; print "A: $a\n";
will print:
A: 1
in PHP -- as opposed to printing "A: avacado" as it would in a language like Perl or JavaScript.
This means you can't use the '||' operator to set a default value:
$a = $fruit || 'apple';
instead, you have to use the '?:' operator:
$a = ($fruit ? $fruit : 'apple');
so i had to go with an extra if encapsulating the ?: operation like so:
if($_POST['x'] || $_SESSION['x']){
$x = ($_POST['x']?$_POST['x']:$_SESSION['x']);
}
or the equivalent also working:
if($_POST['x']){
$x=$_POST['x'];
}elseif($_SESSION['x']){
$x=$_SESSION['x'];
}
I didn't test theses but i presume they would work as well:
$x = ($_POST['x']?$_POST['x']:
($_SESSION['x']?$_SESSION['x']:null)
);
for more variables i would go for a function (not tested):
function mvar(){
foreach(func_get_args() as $v){
if(isset($v)){
return $v;
}
} return false;
}
$x=mvar($_POST['x'],$_SESSION['x']);
Any simple way to achieve the same in php?
EDIT for clarification: in the case we want to use many variables $x=($a||$b||$c||$d);
A simpler approach is to create a function that can accept variables.
public function getFirstValid(&...$params){
foreach($params as $param){
if (isset($param)){
return $param;
}
}
return null;
}
and then to initialize a variable i would do...
var $x = getFirstValid($_POST["x"],$_SESSION["y"],$_POST["z");
the result will be that the var x will be assign the first variable that is set or is set to null if none of the variables pass are set.
explanation:
function getFirstValid accepts a variable number of variable pointers(&...) and loops through each checking if it is set, the first variable encountered that is set will be returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With