tags:

views:

54

answers:

4

Hi Guys,

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?

Thanks in advance!

+4  A: 
Sarfraz
+5  A: 

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

Mark Baker
+3  A: 

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"

Tapdingo
+1  A: 

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

Col. Shrapnel
thanks. i usually clone post to preserve it.
n00b