6

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

Community
  • 1
  • 1
Louis Loudog Trottier
  • 1,367
  • 13
  • 26

5 Answers5

2

Yes you need to use simple ternary operator which you have used within your example along with some other functions of PHP like as of isset or empty functions of PHP. So your variable $x will be assigned values respectively

Example

$x = (!empty($_POST['x'])) ? $_POST['x'] : (!empty($_SESSION['x'])) ? $_SESSION['x'] : NULL;

So the above function depicts that if your $_POST['x'] is set than the value of

$x = $_POST['x'];

else it'll check for the next value of $_SESSION if its set then the value of $x will be

$x = $_SESSION['x'];

else the final value'll be

$x = null;// you can set your predefined value instead of null

$x = (!empty($a)) ? $a : (!empty($b)) ? $b : (!empty($c)) ? $c : (!empty($d)) ? $d : null;

If you need a function then you can simply achieve it as

$a = '';
$b = 'hello';
$c = '';
$d = 'post';

function getX(){
    $args = func_get_args();
    $counter = 1;
    return current(array_filter($args,function($c) use (&$counter){ if(!empty($c) && $counter++ == 1){return $c;} }));
}

$x = getX($a, $b, $c, $d);
echo $x;
Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
2

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.

Keith A
  • 771
  • 6
  • 12
1

Update

I've managed to create a function for you that achieves exactly what you desire, allowing infinite arguements being supplied and fetching as you desire:

function _vars() {
    $args = func_get_args();
    // loop through until we find one that isn't empty
    foreach($args as &$item) {
        // if empty
        if(empty($item)) {
            // remove the item from the array
            unset($item);
        } else {
            // return the first found item that exists
            return $item;
        }
    }
    // return false if nothing found    
    return false;
}

To understand the function above, simply read the comments above.

Usage:

$a = _vars($_POST['x'], $_SESSION['x']);

And here is your:

Example


It is a very simply ternary operation. You simply need to check the post first and then check the session after:

$a = (isset($_POST['x']) && !empty($_POST['x']) ? 
        $_POST['x']
        :
        (isset($_SESSION['x']) && !empty($_SESSION['x']) ? $_SESSION['x'] : null)
    );
Darren
  • 13,050
  • 4
  • 41
  • 79
  • `isset($_POST['x']) && !empty($_POST['x'])` can be replaced by ` !empty($_POST['x'])` only i think. – Sougata Bose Jun 15 '15 at 04:58
  • 1
    @b0s3 I was going to doing that originally, but simply thought the OP might want to see a different alternative ;-) – Darren Jun 15 '15 at 04:59
  • `empty()` will check for bot if the variable is set and it is empty or not. Also `false` will be treated as empty. – Sougata Bose Jun 15 '15 at 05:00
  • @Darren thanks, every alternative can be used depending on the needs. ;-) but there's already enough code in your answer for me to build a function – Louis Loudog Trottier Jun 15 '15 at 05:02
  • 1
    @LouisLoudogTrottier Updated with a function that achieves what you are looking for. – Darren Jun 15 '15 at 05:27
  • 1
    Already had the same function in my original question, except for the reference call `&` and the unset(); Since this seems to the the only way, i will accept your updated answer and carry on. Thanks for all the inputs. – Louis Loudog Trottier Jun 15 '15 at 05:44
  • @louis i went with `empty` instead of `isset` cause you'd already be passing in the arguments so they'd be set. – Darren Jun 15 '15 at 05:48
  • wouldn't this throw a notice with undefined variables? – Keith A Jun 15 '15 at 05:52
  • @keitha - no, because it only checks items in the array, which are set – Darren Jun 15 '15 at 05:54
1

PHP 7 solution: The ?? operator.

$x = expr1 ?? expr2
  • The value of $x is expr1 if expr1 exists, and is not NULL.
  • If expr1 does not exist, or is NULL, the value of $x is expr2.

https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op

Lazac92
  • 145
  • 7
  • At the time of posting this question i don't think PHP 7 was a thing. Much has changed since but still didn't know about this new feature and will definitibely try (and maybe adopt) it. .... And welcome to the community, – Louis Loudog Trottier Jun 06 '20 at 03:37
0

It would be simple -

$x = (!empty($_POST['x']) ? $_POST['x'] :
          (!empty($_SESSION['x']) ? $_SESSION['x'] : null)
     );
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87