Jump to content

Archived

This topic is now archived and is closed to further replies.

vr4lyfe

$ x ? 0 : $ x ... syntax help

Recommended Posts

Hi guys.  I am readying some PHP code and it is using this syntax.

$x->var = $ x ? 0 : $ x;

I know what most its supposed to do (kinda), but just confused about exact syntax of the "?" and ":" notations.

Tried searching PHP.net but couldnt find what I was looking for.  Any expect care to point me to a page I can read or explain this to me?

Share this post


Link to post
Share on other sites
If I'm not wrong, you are using [b]Concise Conditional[/b].
There's an example over http://www.cwhnetworks.com/forums/index.php?showtopic=3243 if you are interested.

Share this post


Link to post
Share on other sites
Thanks for the quick reply.  I googled it .. and it seems a more common name would be the ternary operator.

Very good video on ternary operators @ vtc.com .. its one of their free php tutorial vids. 

Its seem though that these things are good only for echo .. lol .. perhaps its just happens to seem that way because all the example is jsut echo example.

Can I do something like

"(conditional statement) ? function_call(); some_other_functions(); another_function(); : print_error() ;"

instead of just

"(conditional statement) ? 'some text' : 'some other text'; "

Share this post


Link to post
Share on other sites
No, for that you would have to use an if-else construct.

Share this post


Link to post
Share on other sites
I would also suggest you to use if statement, it's much more easier to use.

// Offtopic
Hey Cook, are your Surname [b]Guo[/b] ?
Mine also :P

Share this post


Link to post
Share on other sites
This is the Ternary Operator and is described in the PHP Manual at http://us3.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary

Sometimes it's easier to use an if - then - else, sometimes the ternary operator, and sometimes a switch statement.

Ken

Share this post


Link to post
Share on other sites
Thanks guys.  Consider me informed on ternary operators / concise conditionals now.

;)

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.