Anonymous functions in PHP

Anonymous functions, also known as closures, allow the creation of functions which have no specified name.

Anonymous functions are useful when using functions that require a callback function like array_filter or array_map do:

      $arr = range(0, 10);
      $arr_even = array_filter($arr, function($val) { return $val % 2 == 0; });
      $arr_square = array_map(function($val) { return $val * $val; }, $arr);

Otherwise you would need to define a function that you possibly only use once:

      function isEven($val) { return $val % 2 == 0; }
      $arr_even = array_filter($arr, 'isEven');

      function square($val) { return $val * $val; }
      $arr_square = array_map('square', $arr);

Anonymous functions scan through each element of array on which function is applied.  And pass the value of each element of array to the specified function.  In layman's language, anonymous function is a function without name associated to it.

Add new comment