PHP syntax. Boolean operators, ternary operator and JavaScript

后端 未结 5 1032
挽巷
挽巷 2020-12-21 14:41

In JavaScript I have a habit of using the following fallback evaluation

var width = parseInt(e.style.width) || e.offsetWidth() || 480

mean

相关标签:
5条回答
  • 2020-12-21 14:59

    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:

    0 讨论(0)
  • 2020-12-21 15:00

    its better to be

    $a = isset($_GET['id']) ? $_GET['id'] : 1;
    
    0 讨论(0)
  • 2020-12-21 15:11

    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.

    0 讨论(0)
  • 2020-12-21 15:25

    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.

    0 讨论(0)
  • 2020-12-21 15:25

    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.

    0 讨论(0)
提交回复
热议问题