It’s not valid code, that’s why. You can’t just stick a second variable in each spot and hope the language will deal with it. If you separated it out into two separate expressions, one for each target, it would work as you want it to.
As for the performance thing, it is negligible as @rpkamp said, for the example code. Obviously if the question is because you’re doing this a million times, then your negligible performance differences will mount up. Which is why @benanamen asked about the context.
Your code isn’t clear, though, because as @Rubble said earlier, the variables created inside the if
structure are not the same as the default variables you created before it. If they are not intended to be, then the main difference between code2 and code1 is that, if you use $targetVariable
later in the code, you have a chance in code2 that it will not have been defined at all.
Apart from the first line, where you set $defaultvar
, that is:
code2
$defaultvar=1;
if($condition===$yes) {
$targetVariable=0;
} else {
$targetVariable=1;
}
Do you have a development environment set up? Then stick both bits of code in a loop to execute them a few hundred thousand times, and compare the results. Then you won’t have to bet which is better, you’ll have tangible test data to show you.
They don’t do the same thing as each other, though, so it’s a bit difficult to compare - you’re comparing different jobs rather than different methods of coding the same job.
You could increase the performance of code3 by not assigning a value to the same variable twice, just set it to ‘d’ in the first place.
**code3**
$targetVar1='a';
$targetVar2='b';
if($condition===$yes) {
$targetVariable1='c';
$targetVariable1='d';
}