2

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.

3 Answers 3

1

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.

1
  • Thanks, jleedev, this is exactly what I was looking for. Is there a name for this construct?
    – user151841
    Sep 14, 2010 at 18:31
1

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.

0

Actually, something like

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

Works as advertised in PHP. Thanks, slebetman!

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.