PHP – One Line If Statement – Short If Statement – Condensed If Statement
I always have to look this up, so here it is for easy reference. Sometimes is makes the code look less cluttered if you can express and if in one line.
The one line if statement is also known as the ternary operator if you want to look it up in the PHP documentation. It has also been called the short if statement and the one line if statement.
$x = ($myvalue == 10) ? "the value is 10": "the value is not 10";
If you decide to output $x, if the value of the variable $x is equal to 10, the string “the value is 10″ is printed out. If the value of $x is anything other than 10, the string “the value is not 10″ is printed out.

{ 14 comments… read them below or add one }
Thanks!I was looking for this since a while.Really useful.
As you said Liz a little tired late at night, did a little comprehensive version of my own, even the online PHP manual is a little thin on this topic:
http://webtechmech.com/2009/11/short-php-if-statements.html
Not quite… if $myvalue is 10 then x string “the value is 10″ will be placed in the variable $x.
forgot it again and now looked again in google and it brought me back here lol, just like Crazy (…person who commented 1st)
I need more information about Statement in PHP
cheers been lucking for this for 15min now in google.
Oh! I know I do most of this stuff in the middle of the night, and I am a zombie during daylight hours, but I thought that IS what I said. I’m not sure what you’re trying to tell me.
Thanks for the snippet. I think, however, that you ment if the value of $myvalue is equal to 10 than set the value of $x to “the value is 10″. Otherwise, great!
cool – am always forgetting this and spending ages looking up. Will book mark this and hopefully remember. I need it for perl, but it is all the same.
Useful and quick find, thanks much.
Nice one, just what i’m looking for!
I’ve always wanted someone to tell me that. Thank you!
You rock, thanks! I always have to google this — no more!
Thanks, I also keep forgetting this
, looked it up and ended up here
{ 2 trackbacks }