EtherStingray EtherStingray - 3 years ago 158
PHP Question

PHP foreach value replaced in associative array

how is your day?
Mine is not so good because I can't seem to figure it out. I have a form that looks like this:

<body>
<form action = "opdracht4.7.test.php" method="get">
Uw naam: <input type="text" name="naam"><br>
Uw e-mail: <input type="text" name="email"><br>
<br>
Bevalt deze website? <input type="radio" name="keuze" value="Ja" checked> Ja
<input type="radio" name="keuze" value="Nee"> Nee
<input type="radio" name="keuze" value="Weet niet"> Weet niet <br>
<br>
Uw commentaar: <br>
<textarea name="commentaar"></textarea><br>
<br>
<input type="submit" name="submit" value="submit">
</form>


To process the data I have some requirements that are in a function:

function check_input($input) {
$input = htmlspecialchars($input);
$input = trim($input);
$input = stripslashes($input);

return $input;
}


Now I use $_GET to get all information:

if(isset($_GET['submit'])) {
$form = array($_GET['naam'], $_GET['email'], $_GET['keuze'], $_GET['commentaar']);


so everything is working fine, now I use:

foreach($form as $key => $value) {
$value = check_input($value);
echo $key.' is a '.$value."<br>";
}


But here is where it goes wrong. Every value that passes through $_GET['x'] must be replaced with check_input($value)... But it does not work. The values in the loop are changed but if I quit the foreach loop the $values are still not trimmed, nor adjusted. Can anybody help me out?

Answer Source

I think you are looking for your $form array, but mapped against your check_input function:

if(isset($_GET['submit'])) {
    $form = array($_GET['naam'], $_GET['email'], $_GET['keuze'], $_GET['commentaar']);
    $form = array_map('check_input', $form);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download