6

I want to set a variable to a value, but only if a condition is true.
Instead of doing the following:

if($myarray["foo"]==$bar){  
    $variablename=$myarray["foo"];  
}  

This can end up being quite long if the variable names are long, or perhaps it involves arrays, when it's quite simple what I want to do — set a value if a condition is true.

I would like to use the conditional operator, something like this:

$variablename=($myarray["foo"]=="bar")? $myarray["foo"]......

But this fails because I don't want the variable to be set at all if the statement is false.

Basically, what I'm trying to do is make the first example shorter. Perhaps the conditional operator is not the way though...

Does anyone have any suggestions?

chaos
  • 122,029
  • 33
  • 303
  • 309
  • Your second code sample is not really any shorter than the first (if you remove linebreaks and curly braces in the first). You still reference the array twice... what exactly do you expect to gain from this? – Pavel Minaev Jul 16 '09 at 16:21

9 Answers9

13

It doesn't get much shorter than:

if($condition) $var = $value;
gahooa
  • 131,293
  • 12
  • 98
  • 101
8

IMO, the best way to make your code sample shorter is:

if($myarray["foo"] == $bar)
    $variablename = $myarray["foo"];

FYI, the name of the operator you're asking about isn't "the ternary operator", it's the conditional operator.

Since you ask, a way you could actually use the conditional operator to do what you're asking is:

$myarray['foo'] == $bar ? $variablename = $myarray['foo'] : null;

but that's somewhat horrifically ugly and very unmaintainable.

Community
  • 1
  • 1
chaos
  • 122,029
  • 33
  • 303
  • 309
  • 4
    I think it's safer to always use braces. – Tom Haigh Jul 16 '09 at 16:19
  • 8
    Just wanted to point out, it is actually called the ternary operator http://ca.php.net/ternary#language.operators.comparison.ternary – Evert Jul 16 '09 at 16:26
  • Pfaugh. Shows what Zend knows. – chaos Jul 16 '09 at 16:28
  • 2
    @Evert: not exactly. In the context of PHP, the terms `conditional operator` and `ternary operator` are completely interchangeable, because the conditional is the *only* ternary operator. So as a label on a manual page, it works. It doesn't mean, however, that it's "academically" correct. If PHP had a 2nd ternary operator we wouldn't be having this discussion. – Peter Bailey Jul 16 '09 at 17:07
3

You could do this, but I wouldn't as it is pretty unreadable and stupid:

$myarray["foo"] == $bar ? $variablename = $myarray["foo"] : 0;

or

$myarray["foo"] == $bar && $variablename = $myarray["foo"];
Tom Haigh
  • 57,217
  • 21
  • 114
  • 142
2

Your right, ternary is not the way to go. It's there to handle the if and else part of the statement.

Just stick with the regular if statement.

if($myarray["foo"]==$bar) $variablename=$myarray["foo"];
NotMe
  • 87,343
  • 27
  • 171
  • 245
2

The "problem" you have isn't really a problem. Your example code is very clear and maintainable. I would really say leave it like it is.

You -could- remove the braces, but that will have an impact on maintainability.

Your other alternative is to create a set_if_true(mixed array, string key, boolean conditional) wrapper function. It hides what is really happening but depending on your specific implementation it is a good option. (For instance a configuration type object, or caching backend)

wlashell
  • 888
  • 4
  • 9
  • Agreed. I'll add that you (or others) might want to consult a coding standard for whatever project you might be working with. For example, drupal states "Always use curly braces even in situations where they are technically optional. Having them increases readability and decreases the likelihood of logic errors being introduced when new lines are added." [ref](https://drupal.org/coding-standards) – cdmo Jul 31 '13 at 19:16
2

Put != instead of == and ?: instead of just ?..

$variablename = ($myarray["foo"] != "bar") ?: $myarray["foo"];

is the same as

if($myarray["foo"] != "bar"){} else { $variablename = $myarray["foo"]; }

It might not be the smartest solution but it works. I like this one more

if($myarray["foo"] != "bar") {$variablename = $myarray["foo"]};
Marcello B.
  • 4,177
  • 11
  • 45
  • 65
luka_c
  • 36
  • 1
  • 2
  • 5
0

Set the variable to itself in the false case:

$variablename=($myarray["foo"]=="bar")? $myarray["foo"] : $variablename
Draemon
  • 33,955
  • 16
  • 77
  • 104
  • 1
    Why the downvot? this is perfectly valid – Draemon Jul 16 '09 at 16:17
  • Its not valid, there's a strong chance that will generate a notice. – Alex S Jul 16 '09 at 16:24
  • 1
    Yes it's valid, it just has a precondition. It makes no sense to conditionally set a variable if it may not have been set. If it hasn't been set, and you use the "if" method, you will just cause problems down the line - which is *worse* than a notice at the point of error. – Draemon Jul 16 '09 at 16:45
0

You can put the original expression in the else part of the ternary operation, but if you want to guarantee single evaluation of the expression then you'll have to use a temporary variable and an if statement.

Sam Harwell
  • 97,721
  • 20
  • 209
  • 280
0

Ternary isn't the way, even though it can be written so that ternary works.

The reason is this: you're trying to use it in a way it's not intended, which will make your code awkward for other developers to read.

markh
  • 783
  • 4
  • 10