I’m new to PHP and I’m doing some very simple apps (testing).
I’ve got a form with the following code:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["val1"])) {
$err_val1 = "Error";
} else {
$val1 = test_input($_POST["val1"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
<div class='col-lg-1 center'>
<label>1</label>
<input type='text' class='form-control' name='val1'>
<span class='error'><?php echo (!empty($err_val1)) ? 'Error' : '';?></span>
</div>
Is there a way to use a for (or foreach) loop? Beacause there are 139 "vals" and I’d like to optimize the code avoiding repeat 139 times the same part.
2
Answers
Yes, there is a way:
The untested code above aims to create err_val (like err_val123) if the corresponding value is empty and val (like val123) if the corresponding value is not empty.
extract
gets an associative array of key-value pairs and extracts the keys into variables with the same name and the values being assigned to them. Maybe I’ve done some typos, let me know if this does not work as it is.But this code is not very much readable, why don’t we use arrays instead?
We can iterate over the POSTed object like an associative array:
You could implement the HTML in this way too, if all the children are equal, or separately for the separation of concerns.