Jump to content

correct ternary syntax?


Oziam

Recommended Posts

I have just discovered ternary conditionals and really like the time and space saving,

they seem pretty simple and look neater than a bunch of if else statements crammed together.

 

The thing I would like to know is what is the best or correct method of usng the following;

 

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

 

or do I need the extra parentheses like below;

 

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

 

 

I understand that if I used a second conditon I would need the extra parentheses

 

e.g $page = (isset($_GET['page']) && is_numeric($_GET[page'])) ? $_GET['page'] : '1';

 

Thanks!

 

 

Link to comment
Share on other sites

The extra parenthesis don't appear to be necessary per:

 

http://php.net/manual/en/language.operators.comparison.php

 

However, I tend to always use parenthesis myself, I think it helps to make clear the exact expression that is being evaluated.

 

And just to warn, while ternary expressions can be great time savers and space savers, they're also a huge pain in the behind to go back and read.

 

If you're coding something that others may have to look at, I highly suggest only using ternary expression for extremely simple evaluations, and expanding to an if statement for anything that requires even a little bit of thought.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.