-1

I created a function called multiply() that takes an array of numbers, multiplies each value by a number and return the array:

<?php
  function multiply($arr, $factor)
  {
      $newArr = array_map(function ($number) {
          return $number * $factor; // line 5
      }, $arr);
      return $newArr;
  }
  $array = [2,4,6];
  $factor = 2;
  $result = multiply($array, $factor);
  print_r($result);
?>

The output:

Undefined variable: factor .... on line 5

I don't understand why $factor is undefined in my case?

juanli
  • 583
  • 2
  • 7
  • 19
  • 2
    The anonymous function used in your `array_map()` has it's own scope and `$factor` is not available with your anonymous function's scope. – MonkeyZeus Jul 30 '18 at 16:00
  • please checkout http://php.net/manual/en/functions.anonymous.php to read more about it – schildi Jul 30 '18 at 16:05

1 Answers1

3

The function used in array_map has a different scope and it can't see variables outside of it. You need to use a use keyword and pass $factor as an additional argument so it will be available:

$newArr = array_map(function ($number) use ($factor) {
    return $number * $factor;
}, $arr);