Page 1 of 1
Assign variable to 1 of 3 other variables.
Posted: Wed Jun 05, 2013 12:57 pm
by pickle
Hi all,
I want to assign a variable to the "best" of three variables. By that I mean, for example, I want to assign $x to:
- $a if $a is set
- $b if $a is not set
- $c if neither $a or $b are set.
In Javascript one could do this:
but PHP assigns a boolean value to $x.
I'm currently doing this with a couple ternary operators, but I'm wondering if there's a cleaner way.
Thanks.
Re: Assign variable to 1 of 3 other variables.
Posted: Wed Jun 05, 2013 1:11 pm
by requinix
Using || you would exploit short-circuiting like
Code: Select all
($x = $a) || ($x = $b) || ($x = $c); // needs the parentheses
Personally I'd prefer the ternary operator.
Code: Select all
$x = $a ?: $b ?: $c; // remember that it associates like ($a ?: $b) ?: $c
Re: Assign variable to 1 of 3 other variables.
Posted: Wed Jun 05, 2013 3:13 pm
by pickle
As far as I know, ?: isn't a valid PHP operator. I've changed it a bit to:
[syntax]$x = $a ? $a : ($b ? $b : $c)[/syntax]Which is succinct, but not as pretty as I'd hoped.
Re: Assign variable to 1 of 3 other variables.
Posted: Wed Jun 05, 2013 3:16 pm
by requinix
$x ?: $y is available in 5.3+ and is equivalent to $x ? $x : $y. Shorthand.
Re: Assign variable to 1 of 3 other variables.
Posted: Wed Jun 05, 2013 3:22 pm
by pickle
Ah, I'm running 5.2
Re: Assign variable to 1 of 3 other variables.
Posted: Wed Jun 05, 2013 6:22 pm
by requinix
Yeah, without the shorthand you have to use parentheses

Re: Assign variable to 1 of 3 other variables.
Posted: Thu Jun 06, 2013 1:26 pm
by AbraCadaver
You'll get notices though. Your OP said "if $a is set, etc.". This code is not checking for isset but for non false value.
Re: Assign variable to 1 of 3 other variables.
Posted: Thu Jun 06, 2013 1:57 pm
by pickle
I used the term "is set" because it was more succinct than "has the boolean value of false". In practice, $a, $b can be set to FALSE.
Re: Assign variable to 1 of 3 other variables.
Posted: Fri Jun 07, 2013 1:16 pm
by Weirdan
Re: Assign variable to 1 of 3 other variables.
Posted: Fri Jun 07, 2013 2:47 pm
by requinix
I wish they would alter the short ?: (not necessarily the full ternary form) so that it suppressed undefined variable/offset warnings, like how isset() does with things like
Code: Select all
isset($no_such_variable["key 1"]["key 2"]))
which is equivalent to but does not work exactly the same way as
Code: Select all
isset($no_such_variable, $no_such_variable["key 1"], $no_such_variable["key 1"]["key 2"])
Then dealing with default URL/form variables is much cleaner.
Code: Select all
$page = ($_GET["page"] ?: 1);
// which currently warns so you have to
$page = (isset($_GET["page"]) ? $_GET["page"] : 1);
Re: Assign variable to 1 of 3 other variables.
Posted: Fri Jun 07, 2013 6:15 pm
by Weirdan