Short If Statement in PHP

by Liz Jamieson on August 20, 2007

in Popular Posts,php

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 }

Adrien November 4, 2009 at 5:55 pm

Thanks!I was looking for this since a while.Really useful.

Duncan November 4, 2009 at 2:16 pm

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

Dean October 11, 2009 at 7:14 pm

Not quite… if $myvalue is 10 then x string “the value is 10″ will be placed in the variable $x.

matthew fedak July 17, 2009 at 7:57 am

forgot it again and now looked again in google and it brought me back here lol, just like Crazy (…person who commented 1st)

Alaa hamoud May 11, 2009 at 5:03 pm

I need more information about Statement in PHP

matt March 26, 2009 at 3:54 pm

cheers been lucking for this for 15min now in google.

Liz Jamieson March 19, 2009 at 4:24 pm

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.

Tomas March 19, 2009 at 2:22 am

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!

Jake October 16, 2008 at 10:23 am

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.

Charlie S August 8, 2008 at 12:18 am

Useful and quick find, thanks much.

website bouwers apeldoorn June 10, 2008 at 11:50 am

Nice one, just what i’m looking for!

Liz Jamieson May 30, 2008 at 2:00 pm

I’ve always wanted someone to tell me that. Thank you!

Mike May 27, 2008 at 12:48 pm

You rock, thanks! I always have to google this — no more!

Crazy April 30, 2008 at 4:19 pm

Thanks, I also keep forgetting this :) , looked it up and ended up here

Leave a Comment

CommentLuv Enabled

{ 2 trackbacks }

Previous post:

Next post: