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:
This php code block is called a Ternary Expression. It’s a shortcut for:
$id = $_GET[‘id’];
} else {
$id = false;
}
Sample usage:
$id = isset($_GET[‘id’] ? $_GET[‘id’] : false;
What I’m saying here is
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.
$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.
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.
on Sunday, November 26th, 2006 at 7:43 pm:
hey! I used to be a “fricking n00b”!!! and you as well no doubt.
on Tuesday, December 5th, 2006 at 8:20 am:
What do you think about nested Ternary Expression?
on Thursday, December 7th, 2006 at 9:16 am:
Nested ternary expressions, I avoid.
Mainly because it becomes unreadable and clumsy.