views:

80

answers:

4

So just to better myself I'm wondering which method is better for setting a variable:

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

Method 1: Set the end variable in the if statement

-OR-

Method 2: Set a default variable and only change it's value if needed.

I hope this makes sense.

Thank in advance!

+2  A: 

I think this mostly has to do with personal preference. Any performance improvements will be negligible. Of these two, I would usually go with Method 2. However, I usually use a shorthand form of Method 1 to keep everything readable and on 1 line:

$value = 10;
$x = $value == 10 ? "yes" : "no";
thetaiko
+7  A: 
<?php
    $value = 10;
    $x = 'no';

    if($value == 10){
        $x = 'yes';
    }
?>

Method two.

Vinothbabu
Always explicitly declare all your variables before any conditional blocks. What happens if later on you add an elseif construct, and forget to set the variable. It's good coding practice, and will go a long way to improve readability.
ircmaxell
+1 - Always declare the variable with a value in the first place and change it inside the conditional statement if it evaluates true. In addition, the === comparer should be used in the example as it compares type for type rather than with type-conversion.
Sohnee
A: 

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

Matthew
A: 

In my opinion is better to assign a default value and initialize variables, so i choose the second method.

If something goes wrong runtime you don't have to bother if your variable ($x) has been initialized or not.

$value = 10; $x = $value == 10 ? "yes" : "no";

cirpo
I think you need to wrap the condition into parenthesis.
Luc M