Multiple ways todo an if statement?

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
azz0r_
Forum Commoner
Posts: 27
Joined: Mon Jan 24, 2005 4:15 pm

Multiple ways todo an if statement?

Post by azz0r_ »

I know the old

Code: Select all

if($statement == true)
{$statement = 2;
}

else

{$statement = 1;
}
But I remember reading a wierd method along time ago that (off the top of my head) was like

Code: Select all

if($statment == true){$statement = 2 ? $statement = 1;}
User avatar
SystemWisdom
Forum Commoner
Posts: 69
Joined: Sat Mar 26, 2005 5:54 pm
Location: A Canadian South of the 49th Parallel

Post by SystemWisdom »

Yes, it works like:

Code: Select all

( Condition ) ? True-Value : False-Value;
So you could rewrite an assignment operation like you have above as:

Code: Select all

$statement = ($statement == true) ? 2 : 1;
I hope that helps!
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

I usually use a http://php.net/switch in times when I am expected one of many different possible values.
For example

Code: Select all

switch ($action)
{
     case 'delete' :
     //run delete
     break;

     case 'login' :
     //run login
     break;

     default :
     //if no value has been matched
     //run this
}
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

usually i would write

Code: Select all

if ($condition)
or the negative version

Code: Select all

if (!$condition)
instead of

Code: Select all

if ($condition == true)
if ($condition != true)
if ($condition == false)
if ($condition != false)
User avatar
Pyrite
Forum Regular
Posts: 769
Joined: Tue Sep 23, 2003 11:07 pm
Location: The Republic of Texas
Contact:

Post by Pyrite »

Yes, the (condition) ? true : false; syntax is called the trinary operator or ternary operator. Same as C++ :D
User avatar
harrisonad
Forum Contributor
Posts: 288
Joined: Fri Oct 15, 2004 4:58 am
Location: Philippines
Contact:

re

Post by harrisonad »

using that method also allows you to nest if statements elligibly, such as:

Code: Select all

<?php
$i_am_perfect = ($pointed_nose?($sexy_body?($fair_coplexion? true : false) : false) : false);
?>
d3ad1ysp0rk
Forum Donator
Posts: 1661
Joined: Mon Oct 20, 2003 8:31 pm
Location: Maine, USA

Re: re

Post by d3ad1ysp0rk »

harrisonad wrote:using that method also allows you to nest if statements elligibly, such as:

Code: Select all

<?php
$i_am_perfect = ($pointed_nose?($sexy_body?($fair_coplexion? true : false) : false) : false);
?>
You mean like.. indenting? ;)
Post Reply