Question

I'm going to build simple filter function for $_GET and $_POST. Here is my code.

array_map('clean', $_GET);

function clean($el)
{
  $_GET[] = strip_tags($el);
}

var_dump($_GET);

// result
1 => 'One',
2 => 'Two'

// expected
'first' = 'One'
'second' = 'Two'

How to keep the same structure for key and values?``

Was it helpful?

Solution

The callback to array_map needs to return a value. array_map will call the callback for every value in the array and replace it with the value that is returned. You don't alter the array itself inside the callback.

$_GET = array_map('clean', $_GET);

function clean($el) {
    return strip_tags($el);
}

var_dump($_GET);

But really, since strip_tags already takes one argument and returns one value, this will do the same:

$_GET = array_map('strip_tags', $_GET);

But really really, a blanket strip_tags on all incoming values is a bad idea and doesn't really solve most problems. You need to escape/sanitize each value individually depending on what it is and what it is used for. See The Great Escapism (Or: What You Need To Know To Work With Text Within Text).

OTHER TIPS

You misuse array_map. You should overwrite here the $_GET. and array_map expects the callback to return the element of the new array (for this key).

$_GET = array_map('clean', $_GET);

function clean($el)
{
     return strip_tags($el);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top