syntax help

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mshaker
Forum Newbie
Posts: 2
Joined: Tue Jul 15, 2008 8:53 pm

syntax help

Post 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 "?".
User avatar
omniuni
Forum Regular
Posts: 738
Joined: Tue Jul 15, 2008 10:50 pm
Location: Carolina, USA

Re: syntax help

Post 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
mshaker
Forum Newbie
Posts: 2
Joined: Tue Jul 15, 2008 8:53 pm

Re: syntax help

Post by mshaker »

Thanks Omni. I appreciate the assist!
Post Reply