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']);
Cesar Bielich
  • 4,754
  • 9
  • 39
  • 81
  • Specific to what you are proposing, DON'T! https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – AbraCadaver May 13 '19 at 18:35

1 Answers1

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.

B. Fleming
  • 7,170
  • 1
  • 18
  • 36