Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP syntax. Boolean operators, ternary operator and JavaScript

Tags:

syntax

php

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

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?

like image 262
Dan Avatar asked Jul 10 '26 22:07

Dan


1 Answers

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:

like image 79
Yacoby Avatar answered Jul 13 '26 14:07

Yacoby



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!