tags:

views:

310

answers:

4

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.

+7  A: 

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.
smo
though you gain nothing by doing that, and only make it more complex to read.There are few shortcuts. This is not one.
Alister Bulman
So I shouldn't be doing this, Topbit?
Eikern
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.
smo
In most cases you'll want to use your second example.
smo
Okey, thanks anyway :)
Eikern
Edit that into the answer and you'll get my upvote smo :)
Corporal Touchy
+1  A: 

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.

Zsolt Sz.
+2  A: 

Or smo's solution would work, although IMHO it won't help with the readability of the code.

Zsolt Sz.
+1  A: 

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);

}

phjr