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.
No related posts.


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.
hey! I used to be a “fricking n00b”!!! and you as well no doubt.
What do you think about nested Ternary Expression?
Nested ternary expressions, I avoid.
Mainly because it becomes unreadable and clumsy.