PHP - assigning values ​​inside if statements

I read the other day that assigning values ​​inside if statements is not such a great idea. Honestly, I really use this quite a lot, for example.

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

Any idea why this is not optimal?

+4
source share
4 answers

Not least because the common mistake of beginners is to forget that assignment and equality operators are different, so they can easily lead to confusion or it is difficult to detect errors.

Reading your code is more important than any microoptimization

+13
source

Since it is not a question of being optimal, it is a matter of standards, agreements, conditions, comparisons are needed, not destination.

Don't be confused, Noobs can debug a problem for hours!

+8
source

You can confuse the reader if you accidentally saddened $post == $_POST to $post = $_POST . In general, this does not improve the readability of your code ... In addition, there is often no need to check the assignment with "if"

+4
source

Well, being alone, assignment in a logical operator is not so bad:

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

or

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

we use quite often.
Although he is still in danger of reading or mixing the = and == operators.

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

So, it is better to write in the form

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

although this particular statement is pretty pointless. $ _POST is always set in any reasonable environment and assigns it to another variable, which is not required in most cases

+3
source

Source: https://habr.com/ru/post/1315383/


All Articles