Monday, November 20th, 2006

Ternary Expression in PHP

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.

» Filed under PHP Programming by rvdavid at 0:23.

back to top

4 comments
to Ternary Expression in PHP

  1. Kevin

    on Saturday, November 25th, 2006 at 10:14 pm:

    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. on Sunday, November 26th, 2006 at 7:43 pm:

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

  3. on Tuesday, December 5th, 2006 at 8:20 am:

    What do you think about nested Ternary Expression?

  4. on Thursday, December 7th, 2006 at 9:16 am:

    Nested ternary expressions, I avoid.

    Mainly because it becomes unreadable and clumsy.

Subscribe to comments or TrackBack to Ternary Expression in PHP

Leave a comment





Credits:

© rvdavid blogs: Web Development | Powered by WP 2.3.1

Tree theme modified based on headsetoptions