# Should we have some sort of isset()-like operator with default?

- Thread: https://externals.io/message/62033
- Original archive: https://news-web.php.net/php.internals/62033
- Started by Andrew Faulds on 2012-08-04T19:30:40+00:00
- Messages: 1
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #62033 — Andrew Faulds — 2012-08-04T19:30:40+00:00

URL: https://externals.io/message/62033#62033

Hi there,

In the "Implict isset in ternary operator" thread, the idea of a special 
version of the ternary operator with an isset implied was proposed. I 
don't like this idea very much, but from that I want to suggest some 
sort of "default" operator.

On IRC I had a little discussion about it with nikic (Nikita), salathe 
(IRC realname is Peter) and Tyrael (Ferenc).

Basically, I end up writing code like this a lot:

   if (!isset($relations[$prev])) {
       $relations[$prev] = [];
   }

I don't like isset(), it looks quite ugly to me (although I'm fine with 
empty()). And I think a non-keyword operator for it would be more 
readable, and save space.

My basic idea is summed up by salathe here: https://gist.github.com/3256826

An operator (let's use ? for the time being, whether that becomes the 
actual operator or not) is proposed that functions like isset, so:

   $var? // same as isset(var)

This on its own is already shorter than isset(), and imo, nicer to read:

   if ($var?) { /* ... */ }

However, I also propose a variant on the "var ?" form, which is "var ? 
default", for specifying a default:

   $var ? "default" // same as isset($var) ? $var : "default"

This would allow you to express this:

   if (!isset($_REQUEST['p'])) {
       $page = 'home';
   } else {
       $page = $_REQUEST['p'];
   }

More concisely as:

   $page = $_REQUEST['p'] ? 'home';

But I also propose something like a ?= operator, such that you can fill 
in defaults where a variable doesn't exist:

   $array['thing'] ?= "default value";

So, to some up:

|   $var ?           => isset($var)
   $var ? default   => isset($var) ? $var : default
   $var ?= default  => $var = $var ? default => $var = isset($var) ? $var : default|

Thoughts? This is all hypothetical, of course. It is probably not 
difficult to implement, but I think it needs discussing before 
implementing, I am not going to rush.

Thanks.

-- 
Andrew Faulds
http://ajf.me/
