Re: Implicit isset/isempty check on short-ternary operator
| From: | Hannes Landeholm | Date: | Fri, 08 Apr 2011 09:12:10 +0000 |
| Subject: | Re: Implicit isset/isempty check on short-ternary operator | ||
| References: | 1 2 3 4 5 6 7 8 9 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-51837@lists.php.net to get a copy of this message | ||
Hi. I like Adam's suggestion _a lot_ however I'd also find a third
case very useful.
In addition to:
*********
// standard
$value = isset($a[$key]) ? $a[$key] : 'Not set';
// new ?? double ternary that performs isset check and omits second
expression
$value = $a[$key] ?? : 'Not set';
// new ?? double ternary that performs isset check and uses second
expression
$value = $a[$key] ?? strtoupper($a[$key]) : 'Not set';
*********
I would also like a case where you could:
// new ?? double ternary that performs isset check and uses null
$value = $a[$key]??;
This would replace a lot of ugly code I have where: (the @ operator is ugly)
$value = @$a[$key];
When I want to treat all non existing indexes as containing the null value.
~Hannes
On 8 April 2011 09:02, Adam Richardson <simpleshot@gmail.com> wrote:
>
> >
> >
> >> We need to be careful about changing the beahviour of existing
> > operators.
> >
>
> Indeed.
>
> The '?' character already is special, so using '??' seems like a safe,
> practical approach. However, I'd prefer maintaining the form of the standard
> ternary operator with the colon ($value = $var['bar'] ?? : 'Bar was not
> set'; // value ="Bar was not) so the '??' operator could be applied in any
> situation that one would normally use the standard ternary operator.
>
> // standard
> $value = isset($a[$key]) ? $a[$key] : 'Not set';
>
> // new ?? double ternary that performs isset check and omits second
> expression
> $value = $a[$key] ?? : 'Not set';
>
> // new ?? double ternary that performs isset check and uses second
> expression
> $value = $a[$key] ?? strtoupper($a[$key]) : 'Not set';
>
> Granted, the last example might be infrequent, but I think there's also a
> value in keeping the form of the double ternary (if used at all) the same as
> the standard ternary operator for consistency sake.
>
> Adam
>
> --
> Nephtali: A simple, flexible, fast, and security-focused PHP framework
> http://nephtaliproject.com