![]() |
ternary operator
Ok this is really getting me peeved...what am I doing wrong? The syntax looks just fine...but PHP is complaining..
PHP Code:
I keep getting this error: Parse error: syntax error, unexpected '?' |
This is why I advise people to stay away from ternary operators altogether, they are hard to read and even harder to debug.
|
Quote:
|
PHP Code:
|
Quote:
? just isn't allowed there.The problem is that you're mixing an if statement with a ternary operation when the former is not necessary.Using a ternary operation Note use of parentheses to avoid potential confusion from operator precedence differences. PHP Code:
PHP Code:
|
Thanks guys,
I get it now....I fixed it by using isset() but I don't need that either, I just took it out and it still worked... |
Also on the back of Salathe's mentioning of operator precedence, you could use the
or to give you a different way of achieving the same thing. I can't say I've ever used it like this, but it's one to be aware of nonetheless.php Code:
$szVar1 will equal "Default" if $szVar2 isn't set. |
Quote:
|
If you're going to do that (don't!) then always wrap parentheses around the component parts even if they're not necessary for making things work!
That reminds of questions like: (you can ignore the capitals for this) PHP Code:
|
Quote:
$a = true $b = false $c = false $d = true Please be kind to me!! :-/ |
I'm also using the ternary operator alot. I think it's very well readable. I'm using it alot for HTML output like this:
HTML Code:
<li<?php echo ($i % 4 == 0 ? '" class=first" ' : ''); ?>> |
FWIW while initially ternary operators can be a bit confusing to read, over time I've found them indispensable primarily for reason of writing compact code. For instance, I regularly use a Zend Framework view helper which will return "his" if a user object's gender attribute is set to "m", and "her" if the attribute is set to "f". Using a ternary, I can make this determination within the view helper like so:
PHP Code:
Just my $0.02, Jason == W. Jason Gilmore Author "Easy PHP Websites with the Zend Framework" http://www.easyphpwebsites.com/ |
It may be worth adding that we can nest ternary operators.
It begins to get truly messy when you do this, and that's really when you should begin considering an if statement instead.However: php Code:
|
Quote:
|
| All times are GMT. The time now is 06:14 AM. |
Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0