funeralcrasher: (Default)
funeralcrasher ([personal profile] funeralcrasher) wrote2008-06-23 10:33 am

Stumped.

$num = 10;
function multiply()
{
$num = $num * 10;
}
multiply();
echo $num;


This prints "10" to the screen.

$num = $num * 10;
echo $num;


But this prints "0".

Why is that?

[identity profile] outintospace.livejournal.com 2008-06-23 02:46 pm (UTC)(link)
Because $num in the second example is initialized as nothing (or zero, conceptually). Zero * 10 = zero.

Try:

$num = 10;
$num = $num * 10;
echo $num;

[identity profile] poeticalpanther.livejournal.com 2008-06-23 02:48 pm (UTC)(link)
I'm guessing, I admit, but is it because you're calling a different variable? $a instead of $num?

[identity profile] skywayman.livejournal.com 2008-06-23 04:57 pm (UTC)(link)
Variable scope is your culprit.

The problem is that $num inside multiply() is not the same $num you set to 10. It is a new $num, local to that function.

If you want that function to work you either have to pass the value and return it, or reference the global variable.

// Pass example:

$num = 10;

function multiply($num)
{
$num = ($num * 10);
return $num;
}

$num = multiply($num);

echo $num;

// Global reference example:

$num = 10;

function multiply()
{
global $num;
$num = ($num * 10);
}

multiply();

echo $num;


Required reading: http://us3.php.net/variables.scope