D
D
Don2Quixote2018-02-13 23:08:32
PHP
Don2Quixote, 2018-02-13 23:08:32

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];
?>

At the beginning of the code, the array contains the values. arr[2] = 3. The value arr[2] should be output at the end of the code. In theory, this value should be equal to 4. But 3 is displayed. (Because such a value is indicated in the array at the beginning of the code.) That is, the function call is ignored by the compiler. Why is this happening and how to fix it? geomPr(2, 2);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stalker_RED, 2018-02-13
@Don2Quixote

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.

K
kally, 2018-02-13
@kally

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 question

Ask a Question

731 491 924 answers to any question