Log in

View Full Version : small if statement



Dennis_Gull
02-03-2008, 08:59 PM
Hey, how did that small if statement work in php?

something like.. (variable == something : (this is true) ?(this is false))?

Nile
02-03-2008, 09:12 PM
What the hell are you talking 'bout man?
EDIT: oh, it works something like this:

if(condition)

Dennis_Gull
02-03-2008, 09:24 PM
What the hell are you talking 'bout man?
EDIT: oh, it works something like this:

if(condition)

thats a regular if statement, I talking about the shorter one.

Nile
02-03-2008, 09:28 PM
Theres no shorter if statement, form what I know.

Dennis_Gull
02-03-2008, 09:29 PM
Theres no shorter if statement, form what I know.

yes there is, i just tested different combinations and found out that it works like this:


$nr = 2;

echo ($nr == 2 ? 'yes' : 'no');

it will print yes, but if i write $nr = 3 it will print no

james438
02-03-2008, 10:33 PM
I'm impressed. There really is a shorter way of doing it, however you could be a little clearer in your question. It was a little bit difficult to understand what you were asking about at first.

djr33
02-03-2008, 11:09 PM
I like this compact statement, but it can also be incredibly confusing to read, so use with discretion.

Here's how it works... quite simply, really, but odd to wrap your brain around at first:
condition ? if true do this : else this;
Or: condition [is it true?] do this [else:] this;

So, here's an example:
($a==1) ? echo 1 : echo 'not 1';

However, this can also be embedded and you can get very compact ways of using an if within something else:
echo 'We have '.$a.' item'.($a>1?'s':'').' for sale.';

You can even layer it, where the else portion is a second such statement, allowing you a result for <1, then a result for >5 if desired, making a long statement.

But remember as I said this can become very hard to read.