Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables: overwriting vs if/else [closed]

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

Which is a better 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'm always curious about how software works at the lowest levels.

like image 520
Chris Ullyott Avatar asked May 25 '16 05:05

Chris Ullyott


4 Answers

I would use the first one because it will remove one process. Also it is cleaner than the second one:

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

Or

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

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

like image 115
Majid Abbasi Avatar answered Nov 17 '22 16:11

Majid Abbasi


I prefer the second one

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

I think it is more readable and lower CPU consumer because only one assignment executed at each time. But in the first one when the if is true two assignment executed.

like image 35
Mostafa Vatanpour Avatar answered Nov 17 '22 15:11

Mostafa Vatanpour


The second option is actually slightly faster as it only does one variable assignment when $var_two evaluates to true while the lower level jump operations are comparable in both cases.

On a side note, be careful how conditions like if ($var2) are evaluated as there are many cases that you may not expect to mean false that do. The PHP manual has a great page to clarify that.

like image 30
Julie Pelletier Avatar answered Nov 17 '22 15:11

Julie Pelletier


Its depend which variable you are accessing.

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

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

If you have to define variable in same page then

$formValue = 'x'; 
if(isset($var_two)) {
   $formValue = 'y';
}
like image 1
JiteshNK Avatar answered Nov 17 '22 15:11

JiteshNK