Page 1 of 1

Multiple ways todo an if statement?

Posted: Thu Mar 31, 2005 12:13 pm
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;}

Posted: Thu Mar 31, 2005 12:16 pm
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!

Posted: Thu Mar 31, 2005 12:24 pm
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
}

Posted: Thu Mar 31, 2005 4:21 pm
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)

Posted: Thu Mar 31, 2005 5:53 pm
by Pyrite
Yes, the (condition) ? true : false; syntax is called the trinary operator or ternary operator. Same as C++ :D

re

Posted: Thu Mar 31, 2005 7:31 pm
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);
?>

Re: re

Posted: Thu Mar 31, 2005 7:33 pm
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? ;)