3

i would like to use Ternary Operator for the below code..

<?php 
if($users['active'] == 1 ) 
{ 
    echo 'Yes'; 
} 
else 
{ 
    echo 'No'; 
} 
?>

i tried using this code and it does not work..

<?php ($users['active'] == 1) ? echo "Yes" : echo "No";  ?>

what is wrong?

18
  • 4
    see, this is why you shouldnt be using it. Commented Apr 11, 2011 at 14:26
  • 2
    @Gordon: The ternary operator is amongst the most useful of tools in modern languages. Just because some people have not yet learnt how to use it, does not invalidate its use. Commented Apr 11, 2011 at 14:28
  • 1
    @Orbling a ternary operator is the most useless of all the operators since it is basically only a shorthand if/else. As such, I can easily live without it but definitely not with any of the others. And given that apparently a lot of people fail to understand the concept of expressions, it is good advice to disadvice it's usage. Commented Apr 11, 2011 at 14:33
  • 1
    @Gordon agreed it is just the shorthand, but does it not beautify the code? and moreover if i use it i have somewhat little less code to write. Commented Apr 11, 2011 at 14:43
  • 2
    @Orbling we will have to agree to disagree on all parts Commented Apr 11, 2011 at 15:35

3 Answers 3

12

The echo goes outside of it, not in, it (the ternary operator) is returning a value, not a codeblock.

<?php echo ($users['active'] == 1 ? "Yes" : "No"); ?>
Sign up to request clarification or add additional context in comments.

Comments

1

Just for fun a different way:

$msg = array(true => 'Yes', false => 'No');
echo $msg[(users['active'] == 1)];  

3 Comments

Agreed, it was a sensible suggestion, illustrating a good method to use when there are multiple options. +1
+1 for showing an alternative and not actually suggesting it. :)
@IbrahimAzharArmar: I didn't expect up votes for this ;) But as @Orbling said, if there are more than two options, using this kind of map is often better (as easier to maintain) than if-else or switch constructs...
0
<? if ($users['active']): ?>Yes<? else: ?>No<? endif ?>

15 Comments

Do you seriously think that is better than a ternary? :-|
Since this is echoing something, Col. is assuming you are in a template context so yes, it's more correct this way. It probably needs some explanation tho ;-)
@Col.Shrapnel: I don't see any HTML in the OP's code. Maybe he is writing a shell script. Btw. echoing data is ok.
@Col. thanks for suggesting the alternative but personally i would prefer the above solution because i thinks that is more readable..
@Col. Shrapnel: Obviously it is just my opinion, but I think it is substantially less readable. Also endif is not standard PHP.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.