Answer the question
In order to leave comments, you need to log in
Why is the php script ignoring the function?
<?php
$arr = array(1, 2, 3, 4, 5);
function geomPr($b1, $q) {
$arr[1] = $b1;
for ($n = 1; $n < 11; $n++) {
if ($n == 1) {
$b_previous = $b1;
} else {
$b_previous = $b_previous * $q;
$b = $b_previous * $q;
$arr[$n] = $b;
}
}
}
geomPr(2, 2);
print $arr[2];
?>
geomPr(2, 2);
Answer the question
In order to leave comments, you need to log in
Here it is, your $arr[2]
A function inside itself does something, but the result does not return the same. Let me guess, your first language was js, and now you suddenly find that closures are not in all languages, and even if they are, they do not work quite like that.
There are closures in php , but they are not automatically applied to each function, as in js, and if you really need them, you will have to do it yourself, something like this: https://ideone.com/HvsrC2
And in general, in such simple In some cases, it's easier to pass an array as a parameter: https://ideone.com/JMINtQ
Better yet: https://ideone.com/aWaK70
In this case, it's more obvious that the function will change the $arr array.
You are accessing the external variable $arr.
Inside the function $arr = $b1;
At the end of the function, return the value
return $arr[$n];
}
and when printing:
$geomPr = geomPr(2, 2);
echo $geomPr;
If you don't return a value return $arr[$n]; inside a function, the system does not know what to print or take for calculation.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question