Page 1 of 1

syntax help

Posted: Tue Jul 15, 2008 8:58 pm
by mshaker
I haven't used php that much and it's been a few years. I've notices the usage of this syntax:

function (expression-1) ? (expression-2);

I'm assuming the this means if expression-1 is null, then use expression-2.

Can someone help explain and where inside php can I find using the "?".

Re: syntax help

Posted: Tue Jul 15, 2008 11:18 pm
by omniuni
Very close. The Question Mark is known as the "ternary" operator.

http://php.codenewbie.com/articles/php/ ... age_1.html

I'll summarize a bit:

It's easiest to think of the ternary as a switch; the first term is either true or false, and determines what it evaluates to. Unlike a simple true or false scenario, you assign values.

Think of it this way; switch?if_true:if:false

So, if I have a variable $username that is set from a session, and should display "someone" if it doesn't have the session set:

$username = $_SESSION['username']?$_SESSION['username']:"Someone";

If the session is null, they get the username "Someone", or if it is set, it is assigned as the username.

I hope that helps a bit,
-Omni

Re: syntax help

Posted: Wed Jul 16, 2008 9:55 am
by mshaker
Thanks Omni. I appreciate the assist!