PHP Define var = one or other (aka: $var=($a||$b);)
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;
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)
);