PDA

View Full Version : variable not returning in function


harmor19
07-06-2006, 02:50 AM
I'm sort of copying vBulletin's code that cleans data. If I echo the variable in the function it works but if I return the variable and echo it outside the function it doesn't.

Here is the code.
<?php


function clean($mthd, $arr)
{

if($mthd == "p")
{

foreach (array_keys($arr) as $val)
{
go_clean($val, 'p');
}
}
}

function go_clean(&$val, $mthd)
{

$efinfo = array();

if($mthd == "p")
{
$efinfo[$val] = $_POST[$val];
}

return $efinfo;

//echo "$val: ". $_POST[$val] ."<br /> ";

}

$_POST['username'] = "harmor";
$_POST['password'] = "andrew123";

$data = array('username' => 'STR', 'password' => 'STR', 'age' => 'INT', 'email' => 'STR');
clean('p', $data);

echo $efinfo['username'];


?>

What does the "and" symbol in this function do? go_clean(&$val, $mthd)
I just added it to see if it changed anything but it didn't.

Chris Graham
07-14-2006, 07:10 PM
I take it you're learning to code as this 'cleaning code' does absolutely nothing ;). Here's something that will 'clean' PHP's magic quotes...


<?php


function clean($mthd, $arr)
{

if($mthd == "p")
{

$efinfo = array();
foreach (array_keys($arr) as $val)
{
$efinfo = array_merge($efinfo, go_clean($val, 'p'));
}
return $efinfo;
}
}

function go_clean(&$val, $mthd)
{

$efinfo = array();

if($mthd == "p")
{
$efinfo[$val] = $_POST[$val];
if (get_magic_quotes_gpc()) $efinfo[$val]=stripslashes($efinfo[$val]);
}

return $efinfo;

//echo "$val: ". $_POST[$val] ."<br /> ";

}

$_POST['username'] = "harmor";
$_POST['password'] = "andrew123";

$data = array('username' => 'STR', 'password' => 'STR', 'age' => 'INT', 'email' => 'STR');
$efinfo = clean('p', $data);

echo $efinfo['username'];


?>


Note the key differences:
- we're doing something (using stripslashes) to do some cleaning. I don't know what you're wanting to clean, but this is at least something.
- the clean function will now process the data go_clean returns, putting it all into one big merged array
- the clean function returns the merged array

Now, it's horribly overcomplex code (there's no need for two functions), but hopefully it's a nice example :).

What the "&" does by the way is a bit complex. Basically a normal function treats variables passed into it as new data, and the function could change that data and not affect the data that was passed into the function. If "&" is put before the parameter names then PHP will bind the passed data to the data in the function, so that if you make a change in the function, the actual passed source data will also be changed.