12

I read the other day that assigning values within if statements isn't such a great idea. To be honest i actually use this quite a lot e.g.

if(isset($_POST) && $post = $_POST) {
  print_r($post)
}

Any idea why that isn't optimal?

0

4 Answers 4

22

Not least because it's a common newbie mistake to forget that assignment and equality operators are different, so it can easily lead to confusion or difficult-to-detect bugs.

Readability of your code is more important than any micro-optimisations

Sign up to request clarification or add additional context in comments.

3 Comments

Readability is of course important. if(isset($_POST) && $post = $_POST) is perfectly readable.
It's readable. However, I can't entirely agree with this style of assignment. Why would you assign a variable where an if condition is expected? I'm open to seeing use cases. Thanks.
@BrianAlex Using a function that returns a set of data if a variable is found (valid) or false if it doesn't, for one. if ( $found = $this->searchArray( $sites, 'id', $site ) ) as an actual use case scenario in one of my projects. If the function returns a value the $found variable contains everything about the requested set of data and is used (exclusively) within the IF block, otherwise, the code continues. Can't think of any reason to make the code longer by including it one line above and then just using if ( $found ) when it wouldn't be used anywhere else. Can you?
11

Because it is not about being optimal, it is about standards, conventions, the conditions need comparisons not assignments.

Don't Create The Confusion, Noobs might sit for hours debugging the issue !

Comments

6

Well, being alone, assignment in the logical operator is not that bad:

if ($id = $_GET['id']) {

or

while($row = mysql_fetch_assoc($res)) {

we use pretty often.
Though it's still in danger of readability fault or mixing = and == operators.

But mixing logical and assignment operators in one statement is bad. This is called obfuscation and perl write-only style, makes reading this code harder.

So, it's better to be written as

if(isset($_POST)) {
  $post = $_POST;
  print_r($post);
}

though this particular statement is pretty senseless.
$_POST is always set in any sensible environment and assigning it to another variable not necessary most of time

Comments

4

You could confuse a reader, if you accidentally mistyped $post == $_POST to $post = $_POST. In general it doesn't really improve readability in your code... Besides it is often not necessary to check the assignment with "if"

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.