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
https://forums.phpfreaks.com/topic/215576-correct-ternary-syntax/
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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.