Forum Moderators: coopster

Message Too Old, No Replies

PHP ? if help

         

andrewsmd

5:07 pm on Dec 5, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I have seen the if statement in php with a ? false : true or something like that before. Can anyone explain the syntax for me real quick. I can't find anything on google that will show me a demo of that kind of statement.

Anyango

5:14 pm on Dec 5, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi, Me again ;)

$a=1;
$b=1;

// Normal If{}

if($a==$b)
{
$result="EQUAL";
echo $result;
}

// Compact If{}

$result = $a==$b ? "EQUAL" : "NOT EQUAL";
echo $result;

So we are saying, if a==b then result is "EQUAL" otherwise the result is "NOT EQUAL";

Read it like
L.Hand Side = Condition ? "VALUE IF CONDITION RESULTS TRUE" : "VALUE IF CONDITION RESULTS FALSE"

[edited by: Anyango at 5:15 pm (utc) on Dec. 5, 2008]

coopster

5:53 pm on Dec 5, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Good explanation, Anyango. Here's the manual page reference too. It's called the Ternary Operator [php.net]

andrewsmd

6:41 pm on Dec 5, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



That's what I needed. To me the other kind of if seems easier to read (and nest) this kind of looks like the stupid if syntax in excel. Thanks,

leadegroot

11:45 pm on Dec 5, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Yeah, its really fast to write, but its maintainability is lower because its harder to read.
If its just you working on the project, it can be ok (some people love ternarys) but if you're part of a larger team, they might be better avoided as some people are confused by them,
I avoid them myself.