skip to Main Content

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


  1. Yes, there is a way:

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
      for ($i = 1; $i <= 139; $i++) {
        if (empty($_POST["val" . $i])) {
          extract([("err_val" . $i) => "Error"]);
        } else {
          extract([("val" . $i) => test_input($_POST["val" . $i])]);
        }
      }
    }
    

    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?

    $values = [];
    $errors = [];
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
      for ($i = 1; $i < 139; $i++) {
        if (empty($_POST["val" . $i])) {
          $errors[$i] = "Error";
        } else {
          $values[$i] = test_input($_POST["val" . $i]);
        }
      }
    }
    
    Login or Signup to reply.
  2. We can iterate over the POSTed object like an associative array:

    foreach($_POST as $key=>$value){
        #sanitize
    }
    

    You could implement the HTML in this way too, if all the children are equal, or separately for the separation of concerns.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search