Ternary Expression in PHP

November 20th, 2006 by rvdavid Leave a reply »

After posting on Sitepoint PHP Community Forums again after a long while, I’ve come across some posts which ask what the php code snippet means:

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

This php code block is called a Ternary Expression. It’s a shortcut for:

if ($_GET['id']) {
$id = $_GET['id'];
} else {
$id = false;
}

Sample usage:

#getting the query variable 'id' from the URL 'http://www.rvdavid.net/sampleapp.php?id=143'
$id = isset($_GET['id'] ? $_GET['id'] : false;

What I’m saying here is

if $_GET['id'] is set,
then assign $_GET['id'] to $id
else assign boolean false.

Then you can continue on to use the $id variable in your logic and will be able to determine it’s existence by checking doing a logical not comparison.

#getting the query variable 'id' from the URL 'http://www.rvdavid.net/sampleapp.php?id=143'
$id = isset($_GET['id'] ? $_GET['id'] : false; if (!$id) {
#domain logic here
}

To me, I see it as part of good coding practice. The main advantage of this is that it cuts down 5 lines of code to 1. I’ve heard comments about how it makes code unreadable and that it IS bad practice, but I find it easier to read than nested if statements.

To state the obvious, you shouldn’t really use it for more than what’s been demonstrated else your code could get pretty messy.

if you enjoyed this post, make sure you subscribe to my RSS feed!
You can also follow me on Twitter here.

No related posts.

Advertisement

4 comments

  1. Kevin says:

    Why are you educating n00bs? they’ll take your job for less pay!!!

    j/k

    I’ve answered a few of these on sp also. fricking n00bs.

  2. rvdavid says:

    hey! I used to be a “fricking n00b”!!! and you as well no doubt.

  3. Ben Rowe says:

    What do you think about nested Ternary Expression?

  4. rvdavid says:

    Nested ternary expressions, I avoid.

    Mainly because it becomes unreadable and clumsy.

Leave a Reply

Notify me of followup comments via e-mail. You can also subscribe without commenting.