Re: Implicit isset/isempty check on short-ternary operator
| From: | Rune Kaagaard | Date: | Fri, 08 Apr 2011 13:19:37 +0000 |
| Subject: | Re: Implicit isset/isempty check on short-ternary operator | ||
| References: | 1 2 3 4 5 6 7 8 9 10 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-51838@lists.php.net to get a copy of this message | ||
Dear Internals
I'm very happy that this is getting some attention again. Please allow
me to give my 2 cents too. The text below can also be seen nicely
formatted at https://gist.github.com/909711.
## Intro ##
Isset and IsNotEmpty operators have for sure been a hot topic for several years
now and in my opinion rightly so. The non-DRY style of:
$my_array['my_long_boring_key'] = !empty($my_array['my_long_boring_key'])
? $my_array['my_long_boring_key'] : 'Default value';
$my_array['my_long_boring_key'] = isset($my_array['my_long_boring_key'])
? $my_array['my_long_boring_key'] : 'Default value';
is a true day-to-day hassle and addressing this annoyance would be a
big win for
the PHP community as a whole. As PHP has two keywords
isset and empty that
can check for a non existing variable without throwing errors I think there
should exist two assignment/ternary operators who mirror those.
I have been thinking [1] about the same problem for my meta language Snow and
also ended up using ?? as an isset operator.
## Proposal ##
I propose that two new operators ?? (IssetOperator) and ?!
(NotEmptyOperator) are added. ?? mirrors isset and ?! mirrors
!empty.
They are chainable ad nauseum but not with each other.
They would work like this:
### Example 1 : Ternary shortcut ###
Old syntax:
$a = isset($b) ? $b : 42;
$a = !empty($b) ? $b : 42;
New syntax:
$a = $b ?? 42;
$a = $b ?! 42;
### Example 2 : Direct assignment ###
Old syntax:
$arr['key'] = isset($arr['key']) ? $arr['key'] : 42;
$arr['key'] = !empty($arr['key']) ? $arr['key'] : 42;
New syntax:
$arr['key'] ??= 42;
$arr['key'] ?!= 42;
### Example 3 : Works with statements too ###
Old syntax:
// a)
$tmp = get_stuff('foo');
$a = isset($tmp) ? $tmp : 42;
// b)
$tmp = get_stuff('foo');
$a = !empty($tmp) ? $tmp : 42;
New syntax:
// a)
$a = get_stuff('foo') ?? 42;
// b)
$a = get_stuff('foo') ?! 42;
### Example 4 : Chaining ###
Old syntax [2]:
$a = false;
if (!empty($c) {
$a = $c;
} else {
$tmp = get_stuff();
$a = !empty($tmp) ? $tmp : false;
}
if ($a === false) {
$a = !empty($c) ? $c : 42;
}
New syntax:
$a = $c ?! get_stuff() ?! $b ?! 42;
### Example 5 : Illegal syntax ###
$a = $d ?? $c ?! $b ?? 42; // ?? and ?! cannot be mixed.
## References ##
* [1]: http://code.google.com/p/php-snow/wiki/EmptyIssetOperators
* [2]: This could also be done by nesting ternary operators, but that gets
even more unreadable I think.