Following the php logic, maybe !?? ________________________________ From: Sergii Shymko <ser...@shymko.net> Sent: Sunday, October 29, 2023 4:53:12 PM To: Robert Landers <landers.rob...@gmail.com> Cc: internals <internals@lists.php.net> Subject: Re: [PHP-DEV] Discussion - Anti-null coercion
On Oct 29, 2023, at 1:31 PM, Robert Landers <landers.rob...@gmail.com<mailto:landers.rob...@gmail.com>> wrote: Hello Internals, We currently have a null coercion operator: ??, but we lack an anti-null coercion operator. For example, if I wanted to operate on a header, if-and-only-if it exists, I'd have to write something like this one-liner: fn() => ($_SERVER['HTTP_X_MY_HEADER'] ?? null) ? md5($_SERVER['HTTP_X_MY_HEADER']) : null; Or something like this: function() { if(!empty($_SERVER['HTTP_X_MY_HEADER']) { return md5($_SERVER['HTTP_X_MY_HEADER']); } return null; } This is rather tedious when you have to do it, so, I'd like to discuss adding a new "anti-null coercion" operator: ?! This would collapse the previous verbose code into: fn() => $_SERVER['HTTP_X_MY_HEADER'] ?! md5($_SERVER['HTTP_X_MY_HEADER']; When it is null, it will stay null, thus the above is the same as: fn() => $_SERVER['HTTP_X_MY_HEADER'] ?! md5($_SERVER['HTTP_X_MY_HEADER'] ?? null; It would have a lower precedence than ?? so that the above line would read from left to right without requiring parenthesis/brackets. The operator would only return the right-hand side if the left-hand side exists (aka, not null), otherwise, it would return null. I'm not particularly attached to the ?! syntax (since it does, in fact, look very similar to ?:), so perhaps focusing on the merits of the idea first, then bikeshedding the syntax later would be a good approach? Thoughts? Robert Landers Software Engineer Utrecht NL -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: https://na01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fwww.php.net%2Funsub.php&data=05%7C01%7C%7Cf2f8309c674c4f9137a008dbd8b8b73a%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C638342060099962597%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C&sdata=Frc%2BghvwIS1q%2B79n4joMssXCfeFIHkf7mziuH28XLW0%3D&reserved=0<https://www.php.net/unsub.php> Hi Robert, Why don’t you combine the two examples and use a regular ternary operator along with isset/empty()? fn() => !empty($_SERVER[‘HTTP_X_MY_HEADER’]) ? md5($_SERVER[‘HTTP_X_MY_HEADER’]) : null; It’s only ever so slightly longer than the proposed ?! operator, but way more powerful. You explicitly control the evaluation expression along with the default value. Regards, Sergii