2

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?

5 Answers 5

3

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:

Sign up to request clarification or add additional context in comments.

2 Comments

I trust you. I just wanted to express that you've opened america for me )
You could also do this: $a = $_POST['id'] ?: $_GET['id'] ?: $_SESSION['id'] ?: 1 ; ;-)
3

its better to be

$a = isset($_GET['id']) ? $_GET['id'] : 1;

1 Comment

not quite. if ( !empty( $_GET['id'] ) ) is the same as if ( $_GET['id'] ) except that the former wont throw errors. What you've written is the same as if ( !is_null( $_GET['id'] ) ) except that isset wont throw errors.
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.

Comments

1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.