if ( $a > $b) { $c = $a-$b; }
echo $c;
PHP Notice: Undefined variable... why?
if ( $a > $b) { $c = $a-$b; }
echo $c;
PHP Notice: Undefined variable... why?
That's because $c isn't initialized beforehand and the condition ($a > $b) evaluates to false, therefore not executing the code block.
You'll get an "Undefined variable" notice if you try to read from a variable that didn't have a value before.
Here, you are reading :
$a and $b in the if condition
$a and/or $b don't have a value before the if, you'll get a notice on the if line.$c after the if
$c gets a value assigned to it inside the {} of the if$a <= $becho line.
You should either :
$c
else blockifecho $c into the {} block of the if
$a > $b
BTW : the notice message you're getting should indicate :
Those two informations will help you determine if the problem is with $a and/or $b, or with $c ;-)
You need to declare $c before the if statement
$c = 0;
if ( $a > $b) { $c = $a-$b; }
echo $c;
You will get rid of the notice like this:
if (isset($c)) {
echo $c;
}
But, it would also be better to initialize the $c variable before the if condition.
$c = null;
if ($a > $b) {
$c = $a - $b;
}
echo (int)$c;
Or with isset as well:
$c = null;
if ($a > $b) {
$c = $a - $b;
}
if (isset($c)) {
echo $c;
}