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.
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.
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.
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.
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';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With