PHP syntax. Boolean operators, ternary operator and JavaScript
In JavaScript I have a habit of using the following fallback evaluat开发者_Python百科ion
var width = parseInt(e.style.width) || e.offsetWidth() || 480
meaning width
will get the last non-zero (non-null...) value
However, in php I can't write
$a = $_GET['id'] || 1;
I have to write so
$a = $_GET['id']?$_GET['id']:1;
Which is bad because $_GET['id']
is evaluated twice
Any suggestions?
If you have PHP 5.3 you can simply do:
$a = $_GET['id'] ?: 1;
As from the PHP manual:
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
If you don't have PHP 5.3 or greater you would have to use Sarfraz's (or better, delphist's) suggestion. However, in larger applications I tend to have the request variables wrapped in a way that I can specify a default value in the argument to the function retrieving the request. This has the advantage that it is cleaner (easier to understand) and it doesn't generate warnings if the index doesn't exist in the $_GET variable as I can use things like isset
to check if the array index exists. I end up with something like:
its better to be
$a = isset($_GET['id']) ? $_GET['id'] : 1;
Unfortunately PHP doesn't support that syntax. The best you can do is to use ternary operator like your example:
$a = $_GET['id'] ? $_GET['id'] : 1;
The only option coming in mind for the equivalent stuff is that of using Switch
condition.
Array lookup in a single array is such a marginal amount of time that it really doesn't make a difference.
If you're cascading down a number of arrays, it would be faster to store the value in a temp variable:
$tempId = $example['this']['is']['an']['example']['where']['it\'s']['worth']['storing'];
$a = $tempId ? $tempId : 1;
Otherwise $a = $_GET['id'] ? $_GET['id'] : 1;
is just fine.
PHP 5.3 supports the following syntax:
$a = $_GET['id'] ?: 1;
From the documentation:
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
精彩评论