Which variable setting method is better?

So, in order to better understand myself, I am wondering which method is better to set for a variable:

Code: http://pastie.org/private/jkw9dxplv0ixovvc0omq

Method 1: Set the final variable in the if statement

-OR -

Method 2: Set the default variable and change its value if necessary.

Hope this makes sense.

Thanks in advance!

+4
source share
4 answers
<?php $value = 10; $x = 'no'; if($value == 10){ $x = 'yes'; } ?> 

The second method.

+6
source

I think this is mainly due to personal preferences. Any performance improvements will be minor. Of these two, I would usually go with method 2. However, I usually use an abbreviated form of method 1 to keep everything readable and on 1 line:

 $value = 10; $x = $value == 10 ? "yes" : "no"; 
+3
source

I prefer method 1. Thus, if the case is 10, then $ x is set only once. Otherwise, it is installed once or twice. Not sure if this matters a lot, but it is more readable and logical.

+1
source

In my opinion, it's better to assign a default value and initialize the variables, so I choose the second method.

If something goes wrong, you should not worry if your variable ($ x) was initialized or not.

$ value = 10; $ x = ($ value == 10)? "well no";

+1
source

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


All Articles