MemoryRefresh!

Function / Anonymous   Anonymous



Questions Answers 0%

Pages   0 from 91
Questions   0 from 142

Reset


Anonymous functions, also known as closures, allow the creation of functions which have no specified name.
<?php preg_match("/-([a-z])/", "hello-world", $match); echo $match[0]; // output -w echo $match[1]; // output w echo preg_replace_callback('/-([a-z])/', function($match) { return strtoupper($match[1]); }, 'hello-world'); // output helloWorld Be aware of the ; after function declaration. Without it, the following code will output a Notice (Parse error syntax)
<?php $a = function($var) { $b = "Hello $var"; return $b; }; echo $a('World'); // output Hello World Anonymous functions are useful when using functions that require a callback function like array_filter or array_map do:
<?php $data = array(0, 3, 10); $data = array_filter($data, function($x) { return $x%2 == 0; }); // even var_dump($data); /* array (size=2) 0 => int 0 2 => int 10 */ $data = array(0, 3, 10); $data = array_map(function ($x) { return $x*$x; }, $data); // square var_dump($data); /* array (size=3) 0 => int 0 1 => int 9 2 => int 100 */

Related Pages

Definition
Variables
Anonymous
Reference


0% 100%
 
 
0 pages 91 pages
1) What will the following script output? <?php $a = function($var) { $b = "Hello $var"; return $b; } echo $a('World');





2) What is the output of the following code? <?php function func($x, $x=1, $x=2) { return $x; } print func(3);








Anonymous functions, also known as closures, allow the creation of functions which have no specified name.
<?php preg_match("/-([a-z])/", "hello-world", $match); echo $match[0]; // output -w echo $match[1]; // output w echo preg_replace_callback('/-([a-z])/', function($match) { return strtoupper($match[1]); }, 'hello-world'); // output helloWorld Be aware of the ; after function declaration. Without it, the following code will output a Notice (Parse error syntax)
<?php $a = function($var) { $b = "Hello $var"; return $b; }; echo $a('World'); // output Hello World Anonymous functions are useful when using functions that require a callback function like array_filter or array_map do:
<?php $data = array(0, 3, 10); $data = array_filter($data, function($x) { return $x%2 == 0; }); // even var_dump($data); /* array (size=2) 0 => int 0 2 => int 10 */ $data = array(0, 3, 10); $data = array_map(function ($x) { return $x*$x; }, $data); // square var_dump($data); /* array (size=3) 0 => int 0 1 => int 9 2 => int 100 */

References









Programming

Php
   
Regex
   
MySQL
   
Css
   
jQuery
   
Git
   


References