As a convert from Perl one of the 'features' I miss from Perl is the short-circuit behavior of the or operand (||) and how it can be used to set default values if a passed value is false (0 or ""). Thus, in a passed parameter you can write:

$result = $value || $default;

In perl if the $value variable is false (0 or empty string) then $value will be set to the default value.

In PHP the or operand does not short-circuit in this way. Instead I find myself having to write something like:

$result = ($_REQUEST['value']) ? $_REQUEST['value'] : 'my default value';

This is not only ugly and difficult to read but has the redundancy of naming the $_REQUEST['value'] variable twice.

Another nice feature of using Perl's short-circuit or operand is that defaults can be chained so:

$result = $value || $alt_value || $default;

Will return the default only if $value and $alt_value have both evaluated as false. In other words the first expression that evaluates as true (actually 'not false' would be more accurate) will be returned, all preceding and subsequent values will be ignored.

I don't propose the || operant in PHP should be short-circuited like Perl, but rather either a new operand or new function be added that would have this specific behavior.

As an operand it might look like:

$result = $value ?: $alt_value ?: [ ...] ?: $default; // reusing the terniary operator in this context would be a reasonable mnemonic.

Alternatively if implemented as a function it might look like:

$result = choose($value, $alt_value, [ ... ], $default);

I would be happy to volunteer to do the work to provide this feature if there is enough support for it's inclusion. Thoughts?

Nyk Cowham


--
PHP Development Mailing List <http://www.php.net/>
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to