0

Let say I have an array coming in a $_POST called users

Then I run the following callback real_escape_string. But lets say I have a couple more functions I would like to run as well like clean and trim. Is it possible to do this in one line?

$users = array_map(array($GLOBALS['conn'], 'real_escape_string'), $_POST['users']);
1

1 Answer 1

0

Please review the corresponding section of the PHP documentation for array_map(). Note that the function accepts one callback function and any number of arrays following it, making it impossible to place multiple callbacks into a single array_map() call. If you want to apply multiple functions, you will need to either use nested array_map() calls or pass an anonymous function. Example:

// Nesting.
array_map('trim', array_map('strtoupper', array('  input1  ', ' Input2')));

// Anonymous function.
array_map(function($elem) {
    return trim(strtoupper($elem));
}, array('  input1  ', ' Input2'));

You could also iterate over a list of callbacks like this:

$my_callbacks = array('trim', 'strtoupper');
array_map(function($elem) use ($my_callbacks) {
    foreach($my_callbacks as $callback) {
        $elem = $callback($elem);
    }
    return $elem;
}, array('  input1  ', ' Input2'));

There are plenty of ways to approach this problem. You'll need to select the one that best suits your use case.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.