Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Assigning values within if statements

Tags:

php

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?

like image 321
n00b Avatar asked Jul 12 '10 09:07

n00b


People also ask

Can you declare a variable in an if statement php?

If you're new to the syntax that's used in the code sample, if (int i = 5) { is a perfectly valid way of declaring and defining a variable, then using it inside the given if statement. It allows us to write terser, clearer code, while also avoiding limiting the scope of a variable.


3 Answers

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

like image 126
Mark Baker Avatar answered Oct 23 '22 19:10

Mark Baker


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 !

like image 24
Sarfraz Avatar answered Oct 23 '22 19:10

Sarfraz


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

like image 6
Your Common Sense Avatar answered Oct 23 '22 19:10

Your Common Sense