Reputation: 1475
I'm probably missing something simple here, but I have this function for finding the factors of a number.
function factor($n){
$factors_array = array();
for ($x = 1; $x <= sqrt(abs($n)); $x++)
{
if ($n % $x == 0)
{
$z = $n/$x;
array_push($factors_array, $x, $z);
}
}
return $factors_array;
}
I then want to do something like this...
factor(120);
print_r($factors_array);
This give me nothing though. Any ideas on where I'm going wrong?
Upvotes: 0
Views: 2566
Reputation: 392
You aren't assigning the variable to the return value of the function. As far as the PHP interpreter is concerned, $factors_array
only exists if you're inside the factor()
function. Try this:
$factors_array = factor(120);
print_r($factors_array);
Then you can reuse $factors_array
in other areas of the code.
Have a look at this page for an explanation of why this happens.
Upvotes: 2
Reputation:
just try this:
print_r(factor(120));
Because you can't access $factors_array; outside the function, this is called scope of variable, usually, variables that defined inside function are not available outside, also, variables that are defined outside function are not available inside function...
Read more Variable scope ¶
Upvotes: 0