PHP Conditional Syntax

MarvynDT

Limp Gawd
Joined
Jan 4, 2003
Messages
504
Flash Actionscript has this:

// If condition is true, set foo to "Hello World!", else set foo to "Bye World!"
var foo = (condition == true) ? "Hello World!" : "Bye World!";

What is the syntax to perform the same inline statement in PHP?

EDIT - Apparently it's the same syntax. My code was off, so it wasn't showing the expected results =P
 
love when it's nested like 5 times without parentheses.
 
Meh, I prefer to see

Code:
if (blahblahblah)
{
    do me
}
else
{
    do you
}

than

Code:
(blahblahblah ? do me : do you)

Easier to read :p
 
I think the first time I ever came across a ternary conditional statement I crapped myself.
It was majorly nested like 3 or 4 of them in one...
It took me like 10 minutes just to figure out what the crap it meant.
Seeing those in use anywhere makes me wanna punch a baby.
 
What does a nested ternary block look like?

I would imagine something like this:

Code:
condition == true ? (condition == true ? (condition == true ? do stuff : do other stuff) : (condition == true ? do stuff : do other stuff)) : lol
 
oh no no no, you've used parantheses, what were you thinking, you don't need them
 
Ternary syntax has its uses. For example, when I'm grabbing a bunch of submitted form fields, I find that:
Code:
$val = isset($_POST['val']) ? $_POST['val'] : '';
$val2 = isset($_POST['val2']) ? $_POST['val2'] : '';
.
.
is far easier to write and is not at all difficult to understand. For anything else though, and I prefer the traditional if statement syntax.
 
Ternary syntax has its uses. For example, when I'm grabbing a bunch of submitted form fields, I find that:
Code:
$val = isset($_POST['val']) ? $_POST['val'] : '';
$val2 = isset($_POST['val2']) ? $_POST['val2'] : '';
.
.
is far easier to write and is not at all difficult to understand. For anything else though, and I prefer the traditional if statement syntax.

Bah, that's why we have Request objects that allow us to do things like
Code:
$val1 = Request::get('val', 'defualt');

// or 

$array_of_fields = array('xx', 'yy');
foreach ($array of fields as $field ) {
    $values[$field] = $val1 = Request::get($field, null);
}

If it's in the post you get the value, else you get null. Then you can escape the values in the Request object and make sure we get nice clean data out. :D
 
Bah, that's why we have Request objects that allow us to do things like
Code:
$val1 = Request::get('val', 'defualt');

// or 

$array_of_fields = array('xx', 'yy');
foreach ($array of fields as $field ) {
    $values[$field] = $val1 = Request::get($field, null);
}

If it's in the post you get the value, else you get null. Then you can escape the values in the Request object and make sure we get nice clean data out. :D

Well that certainly looks interesting, but I can't find any references to it on the PHP website. Could you provide a link to a good resource on this technique?
 
Back
Top