0

Let's say I have this code:

if (md5($_POST[$foo['bar']]) == $somemd5) {
  doSomethingWith(md5($_POST[$foo['bar']]);
}

I could shorten that down by doing:

$value = md5($_POST[$foo['bar']];
if ($value == $somemd5) {
  doSomethingWith($value);
}

But is there any pre-set variable that contains the first or second condition of the current if? Like for instance:

if (md5($_POST[$foo['bar']]) == $somemd5) {
  doSomethingWith($if1);
}

May be a unnecessary way of doing it, but I'm just wondering.

2
  • what is foo, a typo? Did you mean $foo? Commented May 28, 2012 at 18:15
  • @ColeJohnson you're right, I did mean $foo. Commented May 28, 2012 at 18:33

3 Answers 3

7

No, but since the assignment itself is an expression, you can use the assignment as the conditional expression for the if statement.

if (($value = md5(..)) == $somemd5) { ... }

In general, though, you'll want to avoid embedding assignments into conditional expressions:

  • The code is denser and therefore harder to read, with more nested parentheses.
  • Mixing = and == in the same expression is just asking for them to get mixed up.
Sign up to request clarification or add additional context in comments.

4 Comments

though you gain nothing by doing that, and only make it more complex to read. There are few shortcuts. This is not one.
So I shouldn't be doing this, Topbit?
I agree this is not exactly "best practice", but I felt the disclaimer at the end of the question, "may be unnecessary...i'm just wondering", gave me some leeway.
In most cases you'll want to use your second example.
1

Since the if is just using the result of an expression, you can't access parts of it. Just store the results of the functions in a variable, like you wrote in your second snippet.

Comments

1

IMHO your 2nd example (quoting below in case someone edits the question) is just ok. You can obscure the code with some tricks, but for me this is the best. In more complicated cases this advise may not apply.

$value = md5($_POST[foo['bar']];

if ($value) == $somemd5) {

 doSomethingWith($value);

}

Comments

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.