views:

46

answers:

3

I'm looking for a semantic or language construct that will simplify some of my if statements. If I have an if statement with an or, where I 'choose' between two values, I'd like to have that chosen variable available later on in the code.

I'll write this in pseudo-code:

if ( x or y ) {
    function(z);
}

Where z is the value of x or y, whichever triggered the if to be true. Otherwise I'm writing

if ( x ) {
    ...
    function(x);
} 

if ( y ) { 
    ...
    function(y);
}

Now in that example the duplication isn't much, but in my actual situation, there are about 6 lines of code that would be identical duplication within each if block. So I write something like:

if ( x )  {
    z = x;
} 

if ( y ) {
   z = y;
}

if ( z ) {
    ...
    function(z);
}

But that just seems so roundabout I suspect that somewhere along the line some guru came up with a nice syntax to make a one-line if. Is there a construct in a language anywhere where I can bind the triggering value into a variable in the subsequent block? What would this structure be called?

The actual situation I'm working in is in PHP, so I realize PHP may not have this capability.

+1  A: 

For this exact situation. You can use the ? operator:

z = x ? x : y;

Which reads: z is (if x is not false) x otherwise it is y.

slebetman
+1  A: 

In Python (also Ruby), the expression x or y evaluates to x if it is true, otherwise y. You could write the statement as f(x or y), or z = x or y.

jleedev
Thanks, jleedev, this is exactly what I was looking for. Is there a name for this construct?
A: 

Actually, something like

if ( $z = ( $x ? $x : $y ) ) {
    function($z);
}

Works as advertised in PHP. Thanks, slebetman!