Is there a way to define a php variable as one or the other, as you would do var x = (y||z) in javascript?
Get screen size, 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 am sending a post variable and I want to save it for later use in the session. What I want to do is set $x to $_POST['x'] if it exists, then check and use $_SESSION['x'] if it exists, and leave $x undefined if none of they are not installed;
$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 such as Perl or JavaScript.
This means that you cannot use '||' statement to set the default value:
$ a = $ fruit || 'An Apple';
instead, you should use the "?:" operator:
$ a = ($ fruit? $ fruit: 'apple');
so I had to go with the extra if encapsulating the operation ?: like this:
if($_POST['x'] || $_SESSION['x']){ $x = ($_POST['x']?$_POST['x']:$_SESSION['x']); }
or the equivalent also works:
if($_POST['x']){ $x=$_POST['x']; }elseif($_SESSION['x']){ $x=$_SESSION['x']; }
I have not tested the theses, but I believe that they will work too:
$x = ($_POST['x']?$_POST['x']: ($_SESSION['x']?$_SESSION['x']:null) );
for a larger number of 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 easy way to achieve the same in php?
EDIT for clarification: in the case when we want to use a lot of variables $x=($a||$b||$c||$d);