PHP syntax. Boolean operators, ternary operator and JavaScript

后端 未结 5 1041
挽巷
挽巷 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:

提交回复
热议问题