Are there any values that should not be trimmed?
Else you could just trim all values using array_map, if $_POST
is not empty:
if(!empty($_POST)) {
$_POST = array_map("trim", $_POST);
}
Hope that helps, not so much code :)
Question
I have a function which verify if all necessary parameters are set and then trim these params. Is it possible? How can/should I pass these parameters per reference?
$error = false;
$error = array();
$posts = array('first_name', 'last_name', 'email',
'telephone', 'address', 'CAP', 'city', 'comments'
//many others
);
$post_error = dieOrTrim(&$posts, &$error);
echo '<pre>';
echo '0'.$_POST['first_name'].'0<br />';
var_dump($error);
var_dump($_POST);
echo '</pre>';
die();
FUNCTION:
function dieOrTrim(&$param) {
foreach($param as &$p){
if(!isset($_POST[$p])){
$error[] = '$_POST['.$p.']';
$post_error = 'ERROR';
return $post_error;
}else{
$_POST[$p] = trim($_POST[$p]);
}
}
}
Entering ' Name ' on first_name field returns:
0 Name 0
array(0) {
}
array(18) {
["first_name"]=>
string(6) " Name "
["last_name"]=>
string(0) ""
["email"]=>
string(0) ""
["telephone"]=>
string(0) ""
["address"]=>
string(3) "+41"
["CAP"]=>
string(3) "(0)"
["city"]=>
string(0) ""
["comments"]=>
string(0) ""
["etc"]=>
string(0) ""
["etc"]=>
string(1) "1"
["etc"]=>
string(0) ""
["etc"]=>
string(0) ""
["etc"]=>
string(0) ""
["etc"]=>
string(0) ""
["etc"]=>
string(0) ""
["etc"]=>
string(0) ""
["etc"]=>
string(1) "1"
["etc"]=>
string(1) "1"
}
OTHER TIPS
The problem I see in your function is that you return immediately after you check !isset($_POST[$p])
. I believe you want to continue on to the next item and operate on that accordingly.
function dieOrTrim($param) {
$post_error = '';
foreach($param as $p){
if(!isset($_POST[$p])){
$post_error = 'ERROR';
continue;
}
// Trim $_POST[$p] if it's set
$_POST[$p] = trim($_POST[$p]);
}
return $post_error;
}
Also, you don't need to pass these by reference since you are not modifying any of the passed parameters.