tags:

views:

281

answers:

6

Could you trim all $_POST vars? because i have a very long list right now for trim each var. looks very unprofessional. i thought trim($_POST); would maybe work but it didnt :]

+6  A: 
foreach($_POST as &$p) $p = trim($p);
Michael Krelin - hacker
Nice and elegant.
ceejayoz
+2  A: 

Quick and simple:

foreach($_POST as $key => $val)
{
    $_POST[$key] = trim($val);
}
zombat
A: 

You can do this with array_walk().

ceejayoz
The callback function for `array_walk` takes two parameters, one for the value and one for the key. But the second parameter of `trim` is intended for a list of character that should be removed from the begin and end. So it wouldn’t work. But with `array_map` it would.
Gumbo
It you wrote a simple wrapper for trim, array_walk would work in place. function aw_trim( } } array_walk($_POST,'aw_trim');
txyoji
+11  A: 

you can do this with array_map:

$_POST = array_map('trim', $_POST);
Greg
Nicer and more elegant.
MiseryIndex
Right, like it even more than my own (and vote for it), wish it could do it in-place without assigning the array.
Michael Krelin - hacker
A: 

The simplest, and cleanest (in my opinion), is to use the built in array_map function:

array_map('trim', $_POST);

You can also apply a method of your own by passing an array as the first callback-parameter like so:

array_map(array('My_Class', 'staticMethod'), $_POST); // Invoke a static method

array_map(array($myObject, 'objectMethod'), $_POST); 
// Invoke $myObject->objectMethod for each element of $_POST
PatrikAkerstrand
array_map works for multidimensional arrays?
inakiabt
@inakiabt: No, but there is a custom implementation of array_map_recursive in the PHP manual user notes.
Alix Axel
@eyze: Thanks. Good to know.
inakiabt
+1  A: 

By careful that $_POST can contain an array. array_map("trim",$elm) will break the array.

mich