Variables: rewrite vs if / else

This is a PHP question, but probably applicable to other languages.

What is the best way to handle variable assignments?

// Use default value and overwrite $var_one = 'x'; if ($var_two) { $var_one = 'y'; } // Use complete if/else if ($var_two) { $var_one = 'y'; } else { $var_one = 'x'; } 

I always wonder how the software works at the lowest levels.

+8
php if-statement
source share
5 answers

I would use the first because it will delete one process. It is also cleaner than the second one:

 $var_one = 'x'; if ($var_two) $var_one = 'y'; 

or

 $var_one = ($var_two ? 'y' : 'x'); 

The code above is even cleaner than my example # 1.

+7
source share

I prefer the second

 if ($var_two) { $var_one = 'y'; } else { $var_one = 'x'; } 

I think this is a more readable and lower CPU consumer, since only one assignment is performed at any given time. But in the first case, if if is true, two assignments are performed.

+2
source share

The second option is actually a little faster, since it has only one variable assignment when $var_two evaluates to true , while lower-level operations are comparable in both cases.

Pay attention to how conditions like if ($var2) will be evaluated, as there are many cases that you might not expect to mean false . The PHP manual has a great page to clarify this.

+2
source share

Depends on the variable you are accessing.

If the variable you are accessing is pre-populated, use the example below

 if(isset($_POST['formValue'])) { $formValue = $_POST['formValue']; } else { $formValue = NULL; } 

If you need to define a variable on the same page, then

 $formValue = 'x'; if(isset($var_two)) { $formValue = 'y'; } 
+1
source share

Both methods of determination are correct and good. Another way to do this: ternary operator .

Here you override the assigned variable with a different "y" depending on $var_two

 $var_one = 'x'; if ($var_two) $var_one = 'y'; 

Use complete if / else. Here you simply assign the value $var_one depending on $var_two .

 if ($var_two) $var_one = 'y'; else $var_one = 'x'; 

As I said, you can do this with the ternary operator , see example, override . existing variable.

 $var_one = x; $var_one = ($var_two) ? 'y' : $var_one; 

again, assignment with new values.

 $var_one = ($var_two) ? 'y' : 'x'; 

Note. . It depends on the code that I need to compare with each other, there are two types, one is assignment, the other is redefinition, I should prefer the ternary operator , if less complexity, or straight forward if.....else .

+1
source share

All Articles