PHP - Function Anonymous functions

Introduction

Anonymous functions, or lambda functions, are functions without a name.

To invoke them, we need to store them as variables.

$addTaxes = function (array &$book, $percentage) { 
    $book['price'] += round($percentage * $book['price'], 2); 
}; 

This preceding anonymous function gets assigned to the variable $addTaxes.

Demo

<?php
     $addTaxes = function (array &$book, $percentage) { 
         $book['price'] += round($percentage * $book['price'], 2); 
     }; /*from  w w  w.j  a  va 2s . co  m*/

     $books = [ 
        ['title' => '2018', 'price' => 8.15], 
        ['title' => 'Java', 'price' => 12.00], 
        ['title' => 'Javascript', 'price' => 3.55] 
     ]; 
     foreach ($books as $index => $book) { 
        $addTaxes($book, $index, 0.16); 
     } 
     var_dump($books); 

?>

Result

Related Topics