Search code examples
phpunique-values

How can I shorten my code with isset values


Im am so lost. Can anyone explain how i can shorten this code. I have hundreds of these! I submit a form with input value. Whenever i dont fill in a value, i get an error. So i made these isset blocks to prevent returning the error. But i seem so unefficient! Please help...thanks

if(isset($_POST['input74'])){
$value74 = $_POST['input74'];
}else{
$value74 = "";#default value
}

if(isset($_POST['input75'])){
$value75 = $_POST['input75'];
}else{
$value75 = "";#default value
}

if(isset($_POST['input76'])){
$value76 = $_POST['input76'];
}else{
$value76 = "";#default value

Solution

  • PHP has support for arrays in forms. You can name your form fields with indexes, e.g. <input type="text" name="input[74]" ... />. Then in PHP, you can access those with a for or foreach loop, because they will be available as an array (i.e. you will have $_POST["input"][74]). You could thus write something like:

    $values = $_POST["input"];
    for ($i = 0; $i < MAX_INPUTS; $i++) {
      if (!isset($values[$i])) {
        $values[$i] = "";  // default value
      }
    }
    

    If for some reason you can't change the HTML side, you could still use a loop to dynamically create the field names and copy the data to an array on the PHP side, something like:

    $value = array();
    for ($i = 0; $i < MAX_INPUTS; $i++) {
      $name = sprintf("input%d", $i);
      if (isset($_POST[$name])) {
        $value[$i] = $_POST[$name];
      } else {
        $value[$i] = "";  // default
      }
    }
    

    In both proposed solutions, you only have some lines of code instead of dozens of repetitions of almost the same lines. In both examples, I assumes that your fields start with input0 and that there is a total of MAX_INPUTS fields. If not all fields exist (e.g. you only have input1, intput2, input74 and input75), you can create an array with the fields numbers:

    $field_list = array(1,2,74,75);
    

    And then use that to check your data (here the example with arrays in HTML field names):

    $values = $_POST["input"];
    foreach ($field_list as $num) {
      if (!isset($values[$num])) {
        $values[$num] = "";  // default value
      }
    }