tags:

views:

72

answers:

4
if ( $a > $b) { $c = $a-$b; }
echo $c;

PHP Notice: Undefined variable... why?

+1  A: 

That's because $c isn't initialized beforehand and the condition ($a > $b) evaluates to false, therefore not executing the code block.

Dennis Haarbrink
+8  A: 

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 :

  • from $a and $b in the if condition
    • if $a and/or $b don't have a value before the if, you'll get a notice on the if line.
  • from $c after the if
    • but $c gets a value assigned to it inside the {} of the if
    • which means it won't get a value if $a <= $b
    • and you'll get a notice on the echo line.


You should either :

  • Assign a default value to $c
    • in an else block
    • or before the if
  • Or move the echo $c into the {} block of the if
    • so it's done only when $a > $b


BTW : the notice message you're getting should indicate :

  • Which variable is undefined when trying to read
  • On which line the problem is

Those two informations will help you determine if the problem is with $a and/or $b, or with $c ;-)

Pascal MARTIN
+1  A: 

You need to declare $c before the if statement

$c = 0;
if ( $a > $b) { $c = $a-$b; }
echo $c;
Rowan
+1  A: 

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;
}
Richard Knop