5 ms·
> || is a short-cutting or comparison operator which returns the first true thing it encounters. I wish. The fact that it actually doesn't is one of the things
by oneeyedpigeon 10y ago
> || is a short-cutting or comparison operator which returns the first true thing it encounters.
I wish. The fact that it actually doesn't is one of the things that really bugs me about PHP:
<?php
var_dump(0 || 42);
The above example will output:
bool(true)
- Mithaldu 10y ago... ok, i gotta admit i had my Perl hat on for that reply.
- claar 10y agoYou were actually correct -- see my above reply.
- TazeTSchnitzel 10y agoPHP does have the shorthand ternary operator `?:`, though, which does what you want here: $ php -r 'var_dump(0 || 42);' bool(true) $ php -r 'var_dump(0 ?: 42);' int(42)
- oneeyedpigeon 10y agoWow. OK, I am a big user of the ternary operator, but I hadn't come across omission of the middle part until now. To be honest, it's not the most accessible syntax (especially if you're coming from another language), but at least I have the option now - thanks! edit: Just to clarify for anyone else unfamiliar with it: $ php -r 'var_dump(42 ?: 0);' int(42)
- rbritton 10y agoDepending on how far back you have to support (e.g., WordPress is still supporting 5.2), omission of the middle part wasn't supported until PHP 5.3.
- TazeTSchnitzel 10y ago5.3 came out seven years ago and isn't even officially supported by the PHP project now, let alone 5.2.
- rbritton 10y agoI know all too well, and you'd never catch me running that on any of my own systems. With a large enough install base, it's not uncommon to have a decent number of people on those older versions though.
- deleted 10y ago[deleted]
- claar 10y agoActually || is short circuiting and behaves exactly as he described, it returns the first true thing it encounters. $ php -a Interactive shell php > echo 1 || die('die'); 1 This echo's 1, it doesn't die.