php inline callback
Asked Answered
A

4

7

A quick question.

Is it possible to declare the callback function inline, in php? For example,

array_filter($input_array, "function($item) { $item['state'] != 0 }")
Assiniboine answered 11/10, 2012 at 10:54 Comment(0)
B
15

Yes, after php 5.3, you could use anonymous function.

array_filter($input_array, function($item) { return $item['state'] != 0; });
Blah answered 11/10, 2012 at 10:56 Comment(3)
Not my case unfortunately.. 5.1 here :(Assiniboine
@Assiniboine Then you could use create_function php.net/manual/en/function.create-function.phpBlah
Note that each line of code inside the anonymous function needs to end with a semicolon.Coloring
M
2

Sure it calls anonymous functions:

array_filter($input_array, function($item) { 
    return $item['state'] != 0;
});
Mata answered 11/10, 2012 at 10:56 Comment(0)
B
0
array_filter($input_array, function($item) { 
    return $item['state'] != 0;
});

This functionality is available from 5.3 or > version of php. In 5.4> version will support $this in inline Anonymous Functions

link for php callback > How do I implement a callback in PHP?

Boathouse answered 19/7, 2014 at 16:13 Comment(1)
this is an identical answer to the already accepted answer. Please avoid doing that.Orthodox
S
0

with create_function? ex:

 $result = array_filter($array, create_function('$a','return preg_match("#\S#", $a);'));     
Stafford answered 19/3, 2020 at 13:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.