Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, better to set the variable before if or use if/else?

So a simple one that I just never could find a straight answer on.

What is better (performance or otherwise):

$var = false;
If ($a == $b) {
    $var = true;
}

or

If ($a == $b) {
    $var = true;
} else {
    $var = false;
}

I've heard arguments for both ways. I find the first cleaner to ensure I have it set, and a little less code too. The pro being that you may only need to set it once without conditional. But the con being that if the argument is true, it gets set twice.

I am assuming the second way is probably best practice

like image 240
DssTrainer Avatar asked Mar 17 '11 16:03

DssTrainer


People also ask

What is the difference between if and else in PHP?

Only, the if..else statement is used in the example. If the given number is 3, it will be evaluated as true in the if statement, so the statement inside the if statement will execute. If it is some other number the PHP else statement part will execute. You may copy the code and try it in your PHP editor.

How to use conditional statements in PHP to execute code?

You can use conditional statements in your code to do this. In PHP we have the following conditional statements: if statement - executes some code if one condition is true if...else statement - executes some code if a condition is true and another code if that condition is false

What is the if-else statement in PHP?

PHP - The if...else Statement The if...else statement executes some code if a condition is true and another code if that condition is false.

What is a variable in PHP?

Think of variables as containers for storing data. A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Remember that PHP variable names are case-sensitive! The PHP echo statement is often used to output data to the screen.


1 Answers

I my opinion the first code is better.

If you accidentally write an IF that doesn't check all cases (you forgot the final else) you will have always the the variabile with a default value setted.

like image 74
dynamic Avatar answered Sep 21 '22 18:09

dynamic