Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to apply a function to an array

Tags:

I am aware of array_walk() and array_map(). However when using the former like so (on an old project) it failed

array_walk($_POST, 'mysql_real_escape_string');

Warning: mysql_real_escape_string() expects parameter 2 to be resource, string given.

So I went with this slightly more ugly version

foreach($_POST as $key => $value) {
    $_POST[$key] = mysql_real_escape_string($value);
}

So why didn't the first way work? What is the best way to map values of an array to a function?

like image 436
alex Avatar asked Feb 16 '10 02:02

alex


People also ask

How do you apply a function to each value in an array?

To apply a function to every item in an array, use array_map() . This will return a new array. $array = array(1,2,3,4,5); //each array item is iterated over and gets stored in the function parameter. $newArray = array_map(function($item) { return $item + 1; }, $array);

Can you put a function in an array?

The simple answer is yes you can place function in an array. In fact, can declare variables and reference them in your function.

How do you apply a function to all elements of an array in JavaScript?

Typically, when you want to execute a function on every element of an array, you use a for loop statement. JavaScript Array provides the forEach() method that allows you to run a function on every element. The forEach() method iterates over elements in an array and executes a predefined function once per element.


2 Answers

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);
like image 55
Gumbo Avatar answered Sep 19 '22 20:09

Gumbo


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;});
like image 39
rynop Avatar answered Sep 17 '22 20:09

rynop