Jump to content

Recommended Posts

hi everyone,

 

i came across the below code. could u pls help me with it? what does get_magic_quotes_gpc do?

 

create_function has 2 variables: "v" (why is v a reference?) and "k" but it uses just "v", no "k".

 

 

if(get_magic_quotes_gpc()){
array_walk_recursive($_GET,create_function('&$v,$k','$v = stripslashes($v);'));
}

 

thanks.

Link to comment
https://forums.phpfreaks.com/topic/271595-what-does-this-piece-of-code-do/
Share on other sites

create_function has 2 variables: "v" (why is v a reference?) and "k" but it uses just "v", no "k".

 

When array_walk_recursive invokes the defined callback function, it will pass it two parameters, the first being the value, the second being the key.  As such, the function needs to expect two parameters in it's definition, hence the $v and $k.  For the purpose of what the function actually does the key is unnecessary so it's not used in the function body but it needs to be in the parameter list to create the correct function signature.

 

$v is a reference so that any changes made to it are reflected in the original array's value.  For example, if you had:

$num = array(1,2,3);
function sq($v, $k){
   $v = $v*$v;
}
array_walk($num, 'sq');
print_r($num);

 

The result of the print_r would show the array $num is the same as it was before, 1,2,3 rather than 1,4,9 as one might expect/desire.  By making the $v parameter a reference though:

$num = array(1,2,3);
function sq(&$v, $k){
   $v = $v*$v;
}
array_walk($num, 'sq');
print_r($num);

 

The code works as expected and $num becomes 1,4,9 after the array_walk call.

If you want to modify the values in the array, yes. If you want to modify the keys, then you have to send it as a reference. Generally speaking, it doesn't make a whole lot of sense using array_walk () without referencing the value. At least not for most applications of it.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.