PHP: Run a function over a list of referenced variables (var_walk)

    This function allows you to run a function over a list of referenced variables. It works a little like array_walk(), but allows an unlimited amount of variables to be referenced.

     

    The function

    function var_walk($func, &...$vars){
        foreach($vars as &$var) $var = $func($var);
    }

     

    You can use it like:

    $username = $_POST['username'];
    $password = $_POST['password'];
    var_walk('urlencode', $username, $password);

     

    It’s quite interesting how it works as PHP allows you to passĀ an argument unpacking operator. Which you can then define as referenced. Having this list of references allows us then to reference each reference again, and run a function over it.

    I was pretty struck to not see a function like this already included within PHP, as it’s something that might come in very handy sometimes.

     

     

    Leave a Reply

    Your email address will not be published. Required fields are marked *