Can someone explain two snippets of code?

This section is for programmers. Please use it for all discussons on interfacing help with your applications and related subjects.

Moderators: Alexander Halser, Michael Schwarzl

Post Reply
Infernal
Posts: 2
Joined: Fri Jun 04, 2010 6:35 pm

Can someone explain two snippets of code?

Unread post by Infernal »

Hi all.

Code: Select all

$testbox = isset($_POST['testbox'])?$_POST['testbox']:null;
I was looking for answer at php tutorial, but unsuccessful.
I need to know what the "?" and the ":" are and how they work.
Greatly appreciated.
Last edited by Infernal on Tue Jun 08, 2010 1:10 pm, edited 1 time in total.
User avatar
Tim Green
Site Admin
Posts: 23153
Joined: Mon Jun 24, 2002 9:11 am
Location: Bruehl, Germany
Contact:

Unread post by Tim Green »

This is called the ternary operator, it is available in most modern programming languages. It is just a shorthand way of doing an IF THEN ELSE branch. A true/false condition comes first, followed by the ? character with one expression and then a second expression after the : character. If the condition evaluates true then the first expression gets performed (or returned, if you are assigning the ternary operator's result to a variable as in your example), if it evaluates false then the second expression gets evaluated.

Quite a few modern languages allow you to nest ternary operators. JavaScript does, but my PHP is a bit rusty at the moment, I'm not 100% sure if it does, but probably. This means you can place additional ternary operator sequences in the expressions following the ? and/or : characters. Doing this to great depth is a wonderful way to create bugs that are almost impossible to find. 8)
Regards,
Tim (EC Software Documentation & User Support)

Private support:
Please do not email or PM me with private support requests -- post to the forum directly.
Post Reply