Easy way to apply a function to an array

I know the OP asked to call a function, however in the cases where you do not really need to call a function you can define an anonymous one:

$ids = [1,2,3];
array_walk($ids,function(&$id){$id += 1000;});

mysql_real_escape_string() won't work unless you've made a mysql connection first. The reason it is so cool is that it will escape characters in a way to fit the table type. The second [optional] argument is a reference to the mysql connection.

$_POST is always set up as key->value. So, you array_walk calls mysql_real_escape_string(value, key). Notice the second argument is not a reference.

That is why it does not work. There are several solution already mentioned above.


The callback function passed to array_walk is expected to accept two parameters, one for the value and one for the key:

Typically, funcname takes on two parameters. The array parameter's value being the first, and the key/index second.

But mysql_real_escape_string expects the second parameter to be a resource. That’s why you’re getting that error.

Use array_map instead, it only takes the value of each item and passes it to the given callback function:

array_map('mysql_real_escape_string', $_POST);

The second parameter will be omitted and so the last opened connection is used.

If you need to pass the second parameter, you need to wrap the function call in another function, e.g. an anonymous function:

array_map(function($string) use ($link) { return mysql_real_escape_string($string, $link); }, $_POST);

It's because the mysql_real_escape_string is being given two parameters, both string.

http://php.net/manual/en/function.mysql-real-escape-string.php

http://www.phpbuilder.com/manual/en/function.array-map.php:

array_map() returns an array containing all the elements of arr1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()

you could do

function myescape($val)
{
    return mysql_real_escape_string($val);
}

... then

array_walk($_POST, 'myescape');

Tags:

Php

Arrays