Easy way to apply a function to an array

前端 未结 7 703
無奈伤痛
無奈伤痛 2020-12-03 14:31

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,          


        
相关标签:
7条回答
  • 2020-12-03 15:03

    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);
    
    0 讨论(0)
提交回复
热议问题