0

I thought I'd seen this before, but I'm not finding it anywhere.

If I have a variable and want to assign it a new value if a condition is true, but otherwise leave the variable alone, is there a way to do this without repeating the variable/original value?

The "long ways" would be:

if($condition == TRUE) {
     $og_value = "New Value";
}

Or:

$og_value = ($condition == TRUE) ? "New Value" : $og_value;

But I seem to remember there is a trick, either built into assignment operators or using bitwise operators to only set $og_value if $condition is true, otherwise it short circuits and leaves $og_value as it was before the assignment/comparison.

2

1 Answer 1

1

I think you are looking for:

$condition && $og_value = "New Value";
Sign up to request clarification or add additional context in comments.

7 Comments

This is correct, but let me just address the OP and say that this is atrocious and he should never use this.
@RafeKettler - Atrocious to look at or actually bad practice/anti-pattern?
@stewe - Thanks! But that looks like it sets them both (even if it doesn't). Is that what makes it atrocious like Rafe says?
@RafeKettler Well, the first thing I noticed is that the order matters, which makes sense, but it took me 5 minutes to figure out why it wasn't working. Second thing is, I still have to repeat the variable name if I just want to set it's value if it's not already set, with the above it would be !$og_value && $og_value = "default"; And that is atrocious even to me.
@Anthony: An if-statement is the best choice because everything else may lead to confusion about what the program really does (maybe you experienced that ^^). Especially if the code gets bigger, with lots of people working on it, readability becomes more and more important.
|

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.