Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Define var = one or other (aka: $var=($a||$b);)

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);

like image 333
Louis Loudog Trottier Avatar asked Jun 15 '15 04:06

Louis Loudog Trottier


1 Answers

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.

like image 176
Keith A Avatar answered Oct 15 '22 08:10

Keith A