Easy way to apply a function to an array

前端 未结 7 702
無奈伤痛
無奈伤痛 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 14:37

    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.

    0 讨论(0)
  • 2020-12-03 14:41

    I had trouble using the accepted answer as it caused me errors for reasons I couldn't work out. So for anyone having trouble with array_walk or array_map I found this to work.

    foreach($_POST as $pk => $pv) $_POST[$pk] = mysql_real_escape_string($pv);
    
    0 讨论(0)
  • 2020-12-03 14:43

    PHP 7.4 style:

    $link = mysqli_connect("localhost", "my_user", "my_password", "world");
    
    array_map(fn($string) => mysqli_real_escape_string($string, $link), $_POST);
    
    0 讨论(0)
  • 2020-12-03 14:51

    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');
    
    0 讨论(0)
  • 2020-12-03 14:57

    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;});
    
    0 讨论(0)
  • 2020-12-03 14:58

    http://php.net/manual/en/function.array-walk.php says that array_walk will call the function with 2 arguments, the value and the key. You should write a new function to wrap mysql_real_escape_string. Something like:

    function wrapper($val, $key){
        return mysql_real_escape_string($val);
    }
    

    And then:

    array_walk($_POST, 'wrapper');
    

    Sorry if my PHP is not correct, but I think you'll catch the general idea.

    0 讨论(0)
提交回复
热议问题