ehm
ehm

Reputation: 23767

PHP: return a part of an if () { }

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.

Upvotes: 0

Views: 909

Answers (3)

smo
smo

Reputation: 913

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.

Upvotes: 7

Paweł Hajdan
Paweł Hajdan

Reputation: 18552

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

}

Upvotes: 1

Zsolt Szeberenyi
Zsolt Szeberenyi

Reputation: 437

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.

Upvotes: 1

Related Questions