3

PHP functions such as array_map and array_filter take an array, and a function as arguments.

EG:

$result = array_map(function (el) {
// do stuff
}, $elements)

Is it possible to pass a standard php function the same way?

Something along the lines of $result = array_map(boolval, $elements)

EDIT The above example throws the error Undefined constant boolval

3
  • 1
    why not ? give it a try! Commented Sep 27, 2018 at 19:48
  • Undefined constant boolval Commented Sep 27, 2018 at 19:49
  • It should be : $result = array_map('boolval', $elements); Commented Sep 27, 2018 at 19:50

3 Answers 3

5

You need to pass the function (user-defined OR builtin) name as a string in the parameter of array_map function.

Do the following:

$result = array_map('boolval', $elements);
Sign up to request clarification or add additional context in comments.

2 Comments

That works! is there any way to get the actual callable object boolval, other than by passing it's name in a string?
@indieman If you specifically want a function instead of just a string, you could wrap the builtin function in a closure, like $boolval = function($x) { return boolval($x); };. I really can't think of any context where this would be needed, though. A callable type declaration should always convert the string to its corresponding function.
1

Normally, you just run

$result = array_map('functionName', $array);

If it's a class function, you have to pass the object instance and the function name in an array.

$result = array_map([$objectInstance, 'functionName'], $array);

If the function is in the same class, then

$result = array_map([$this, 'functionName'], $array);

Comments

0

When you have any function which take a callable as a parameter PHP function is passed by its name as a string. And any PHP built-in or user-defined function can be used, except language constructs such as: array(), echo, empty(), eval(), exit(), isset(), list(), print or unset(). You can read more here PHP Callbacks/Callables.

You can call any function by passing it name as a first parameter of call_user_func_array and second parameters an array with parameters that the function you want to call take

$result = call_user_func_array('array_map', array(
    'boolval', array(
        "1", 
        '0', 
        true, 
        false
    )
));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.