Is it possible to make this PHP code shorter?Unicode parsing in PHPPopulating form contents from GET -...

How can I be pwned if I'm not registered on that site?

Second-rate spelling

Equivalent to "source" in OpenBSD?

Hacker Rank: Array left rotation

If nine coins are tossed, what is the probability that the number of heads is even?

Accessing something inside the object when you don't know the key

How to acknowledge an embarrassing job interview, now that I work directly with the interviewer?

What's the difference between a cart and a wagon?

Whom do I have to contact for a ticket refund in case of denied boarding (in the EU)?

Is divide-by-zero a security vulnerability?

Understanding Kramnik's play in game 1 of Candidates 2018

Why do members of Congress in committee hearings ask witnesses the same question multiple times?

Compare four integers, return word based on maximum

You'll find me clean when something is full

Why does the 31P{1H} NMR spectrum of cis-[Mo(CO)2(dppe)2] show two signals?

Six real numbers so that product of any five is the sixth one

Is there a frame of reference in which I was born before I was conceived?

Why is working on the same position for more than 15 years not a red flag?

How to deny access to SQL Server to certain login over SSMS, but allow over .Net SqlClient Data Provider

How do I construct an nxn matrix?

Pure Functions: Does "No Side Effects" Imply "Always Same Output, Given Same Input"?

When was drinking water recognized as crucial in marathon running?

How can atoms be electrically neutral when there is a difference in the positions of the charges?

Should I choose Itemized or Standard deduction?



Is it possible to make this PHP code shorter?


Unicode parsing in PHPPopulating form contents from GET - especially radio buttonsContact information validationMake code more memory efficient, or shorterEmail Template Parser PHP ClassExtracting relevant form data to an arrayAdding border to required fields when fields are emptyMy included in every script file - follow-up -1Is it possible to make easier this code?Check PHP validation code













3












$begingroup$


I need help with this code. How can I make it shorter? How can I create an array with the names, for example, errors, and modify code without so many If statements? I still can't solve it. I'm a beginner in PHP.


$error1 = $error2 = $error3 = $error4 = $error5 = $error6 = $error7 = $error8 = ""; 

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$error1 = "fill in fname";
}
if (empty($_POST["lname"])) {
$error2 = "fill in lname";
}
if (empty($_POST["street"])) {
$error3 = "fill in street";
}
if (empty($_POST["city"])) {
$error4 = "fill in city";
}
if (empty($_POST["postcode"])) {
$error5 = "fill in postcode";
}
if (empty($_POST["country"])) {
$error6 = "fill in country";
}
if (empty($_POST["email"])) {
$error7 = "fill in email";
}
if (empty($_POST["phone"])) {
$error8 = "fill in phone";
}
if (empty($_POST["fname"]) ||
empty($_POST["lname"]) ||
empty($_POST["street"]) ||
empty($_POST["city"]) ||
empty($_POST["postcode"]) ||
empty($_POST["country"]) ||
empty($_POST["email"]) ||
empty($_POST["phone"])) {
} else {
$form_items = $_POST;
$document = new DOMDocument("1.0", "utf-8");
if (is_file('form_data.xml'))
{
$document->load("form_data.xml");
$xmlko = $document->getElementsByTagName('xml')->item(0);
}
else
{
$xmlko = $document->createElement("xml");
$document->appendChild($xmlko);
$xmlko = $document->getElementsByTagName('xml')->item(0);
}
$form = $document->createElement("form");
$new_user = $document->createElement("user");
foreach ($form_items as $ite => $val) {
$this_user = $document->createElement($ite, $val);
$new_user->appendChild($this_user);
}
$form->appendChild($new_user);
$xmlko->appendChild($form);
$document->save("form_data.xml");

}
}

?>


Here is HTML code. Everything is in one PHP file.



<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>form</title>
<link rel="stylesheet" href="CSS/styly.css">
</head>
<body>
<h1>FORM</h1>
<form action="" method="post">
<p>FName:</p>
<input type="text" name="fname"/><span class="error"><?php echo $error1?></span>
<p>LName:</p>
<input type="text" name="lname"/><span class="error"><?php echo $error2?></span>
<p>Street:</p>
<input type="text" name="street"/><span class="error"><?php echo $error3?></span>
<p>City:</p>
<input type="text" name="city"/><span class="error"><?php echo $error4?></span>
<p>Postcode:</p>
<input type="text" name="postcode"/><span class="error"><?php echo $error5?></span>
<p>Country:</p>
<input type="text" name="country"/><span class="error"><?php echo $error6?></span>
<p>E-mail:</p>
<input type="text" name="email"/><span class="error"><?php echo $error7?></span>
<p>Phone:</p>
<input type="text" name="phone"/><span class="error"><?php echo $error8?></span>
<input type="submit" value="SUBMIT"/>
</form>

<?php

$document = new DOMDocument("1.0", "utf-8");
if (is_file('form_data.xml')) {
$document->load("form_data.xml");
$users = $document->getElementsByTagName("user");

echo "<table>";

echo '<tr>';
foreach($users->item(0)->childNodes as $data) {
echo '<th>'.$data->nodeName."</th>";
}
echo '</tr>';


foreach($users as $user){
echo '<tr>';
foreach($user->childNodes as $data) {
echo '<td>'.$data->nodeValue."</td>";
}
echo '</tr>';
}

echo "</table>";
}

?>

</body>
</html>


All data from the HTML form is inserted into the table below the form.
Thanks in advance!










share|improve this question











$endgroup$

















    3












    $begingroup$


    I need help with this code. How can I make it shorter? How can I create an array with the names, for example, errors, and modify code without so many If statements? I still can't solve it. I'm a beginner in PHP.


    $error1 = $error2 = $error3 = $error4 = $error5 = $error6 = $error7 = $error8 = ""; 

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["fname"])) {
    $error1 = "fill in fname";
    }
    if (empty($_POST["lname"])) {
    $error2 = "fill in lname";
    }
    if (empty($_POST["street"])) {
    $error3 = "fill in street";
    }
    if (empty($_POST["city"])) {
    $error4 = "fill in city";
    }
    if (empty($_POST["postcode"])) {
    $error5 = "fill in postcode";
    }
    if (empty($_POST["country"])) {
    $error6 = "fill in country";
    }
    if (empty($_POST["email"])) {
    $error7 = "fill in email";
    }
    if (empty($_POST["phone"])) {
    $error8 = "fill in phone";
    }
    if (empty($_POST["fname"]) ||
    empty($_POST["lname"]) ||
    empty($_POST["street"]) ||
    empty($_POST["city"]) ||
    empty($_POST["postcode"]) ||
    empty($_POST["country"]) ||
    empty($_POST["email"]) ||
    empty($_POST["phone"])) {
    } else {
    $form_items = $_POST;
    $document = new DOMDocument("1.0", "utf-8");
    if (is_file('form_data.xml'))
    {
    $document->load("form_data.xml");
    $xmlko = $document->getElementsByTagName('xml')->item(0);
    }
    else
    {
    $xmlko = $document->createElement("xml");
    $document->appendChild($xmlko);
    $xmlko = $document->getElementsByTagName('xml')->item(0);
    }
    $form = $document->createElement("form");
    $new_user = $document->createElement("user");
    foreach ($form_items as $ite => $val) {
    $this_user = $document->createElement($ite, $val);
    $new_user->appendChild($this_user);
    }
    $form->appendChild($new_user);
    $xmlko->appendChild($form);
    $document->save("form_data.xml");

    }
    }

    ?>


    Here is HTML code. Everything is in one PHP file.



    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>form</title>
    <link rel="stylesheet" href="CSS/styly.css">
    </head>
    <body>
    <h1>FORM</h1>
    <form action="" method="post">
    <p>FName:</p>
    <input type="text" name="fname"/><span class="error"><?php echo $error1?></span>
    <p>LName:</p>
    <input type="text" name="lname"/><span class="error"><?php echo $error2?></span>
    <p>Street:</p>
    <input type="text" name="street"/><span class="error"><?php echo $error3?></span>
    <p>City:</p>
    <input type="text" name="city"/><span class="error"><?php echo $error4?></span>
    <p>Postcode:</p>
    <input type="text" name="postcode"/><span class="error"><?php echo $error5?></span>
    <p>Country:</p>
    <input type="text" name="country"/><span class="error"><?php echo $error6?></span>
    <p>E-mail:</p>
    <input type="text" name="email"/><span class="error"><?php echo $error7?></span>
    <p>Phone:</p>
    <input type="text" name="phone"/><span class="error"><?php echo $error8?></span>
    <input type="submit" value="SUBMIT"/>
    </form>

    <?php

    $document = new DOMDocument("1.0", "utf-8");
    if (is_file('form_data.xml')) {
    $document->load("form_data.xml");
    $users = $document->getElementsByTagName("user");

    echo "<table>";

    echo '<tr>';
    foreach($users->item(0)->childNodes as $data) {
    echo '<th>'.$data->nodeName."</th>";
    }
    echo '</tr>';


    foreach($users as $user){
    echo '<tr>';
    foreach($user->childNodes as $data) {
    echo '<td>'.$data->nodeValue."</td>";
    }
    echo '</tr>';
    }

    echo "</table>";
    }

    ?>

    </body>
    </html>


    All data from the HTML form is inserted into the table below the form.
    Thanks in advance!










    share|improve this question











    $endgroup$















      3












      3








      3





      $begingroup$


      I need help with this code. How can I make it shorter? How can I create an array with the names, for example, errors, and modify code without so many If statements? I still can't solve it. I'm a beginner in PHP.


      $error1 = $error2 = $error3 = $error4 = $error5 = $error6 = $error7 = $error8 = ""; 

      if ($_SERVER["REQUEST_METHOD"] == "POST") {
      if (empty($_POST["fname"])) {
      $error1 = "fill in fname";
      }
      if (empty($_POST["lname"])) {
      $error2 = "fill in lname";
      }
      if (empty($_POST["street"])) {
      $error3 = "fill in street";
      }
      if (empty($_POST["city"])) {
      $error4 = "fill in city";
      }
      if (empty($_POST["postcode"])) {
      $error5 = "fill in postcode";
      }
      if (empty($_POST["country"])) {
      $error6 = "fill in country";
      }
      if (empty($_POST["email"])) {
      $error7 = "fill in email";
      }
      if (empty($_POST["phone"])) {
      $error8 = "fill in phone";
      }
      if (empty($_POST["fname"]) ||
      empty($_POST["lname"]) ||
      empty($_POST["street"]) ||
      empty($_POST["city"]) ||
      empty($_POST["postcode"]) ||
      empty($_POST["country"]) ||
      empty($_POST["email"]) ||
      empty($_POST["phone"])) {
      } else {
      $form_items = $_POST;
      $document = new DOMDocument("1.0", "utf-8");
      if (is_file('form_data.xml'))
      {
      $document->load("form_data.xml");
      $xmlko = $document->getElementsByTagName('xml')->item(0);
      }
      else
      {
      $xmlko = $document->createElement("xml");
      $document->appendChild($xmlko);
      $xmlko = $document->getElementsByTagName('xml')->item(0);
      }
      $form = $document->createElement("form");
      $new_user = $document->createElement("user");
      foreach ($form_items as $ite => $val) {
      $this_user = $document->createElement($ite, $val);
      $new_user->appendChild($this_user);
      }
      $form->appendChild($new_user);
      $xmlko->appendChild($form);
      $document->save("form_data.xml");

      }
      }

      ?>


      Here is HTML code. Everything is in one PHP file.



      <!DOCTYPE html>
      <html>
      <head>
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <title>form</title>
      <link rel="stylesheet" href="CSS/styly.css">
      </head>
      <body>
      <h1>FORM</h1>
      <form action="" method="post">
      <p>FName:</p>
      <input type="text" name="fname"/><span class="error"><?php echo $error1?></span>
      <p>LName:</p>
      <input type="text" name="lname"/><span class="error"><?php echo $error2?></span>
      <p>Street:</p>
      <input type="text" name="street"/><span class="error"><?php echo $error3?></span>
      <p>City:</p>
      <input type="text" name="city"/><span class="error"><?php echo $error4?></span>
      <p>Postcode:</p>
      <input type="text" name="postcode"/><span class="error"><?php echo $error5?></span>
      <p>Country:</p>
      <input type="text" name="country"/><span class="error"><?php echo $error6?></span>
      <p>E-mail:</p>
      <input type="text" name="email"/><span class="error"><?php echo $error7?></span>
      <p>Phone:</p>
      <input type="text" name="phone"/><span class="error"><?php echo $error8?></span>
      <input type="submit" value="SUBMIT"/>
      </form>

      <?php

      $document = new DOMDocument("1.0", "utf-8");
      if (is_file('form_data.xml')) {
      $document->load("form_data.xml");
      $users = $document->getElementsByTagName("user");

      echo "<table>";

      echo '<tr>';
      foreach($users->item(0)->childNodes as $data) {
      echo '<th>'.$data->nodeName."</th>";
      }
      echo '</tr>';


      foreach($users as $user){
      echo '<tr>';
      foreach($user->childNodes as $data) {
      echo '<td>'.$data->nodeValue."</td>";
      }
      echo '</tr>';
      }

      echo "</table>";
      }

      ?>

      </body>
      </html>


      All data from the HTML form is inserted into the table below the form.
      Thanks in advance!










      share|improve this question











      $endgroup$




      I need help with this code. How can I make it shorter? How can I create an array with the names, for example, errors, and modify code without so many If statements? I still can't solve it. I'm a beginner in PHP.


      $error1 = $error2 = $error3 = $error4 = $error5 = $error6 = $error7 = $error8 = ""; 

      if ($_SERVER["REQUEST_METHOD"] == "POST") {
      if (empty($_POST["fname"])) {
      $error1 = "fill in fname";
      }
      if (empty($_POST["lname"])) {
      $error2 = "fill in lname";
      }
      if (empty($_POST["street"])) {
      $error3 = "fill in street";
      }
      if (empty($_POST["city"])) {
      $error4 = "fill in city";
      }
      if (empty($_POST["postcode"])) {
      $error5 = "fill in postcode";
      }
      if (empty($_POST["country"])) {
      $error6 = "fill in country";
      }
      if (empty($_POST["email"])) {
      $error7 = "fill in email";
      }
      if (empty($_POST["phone"])) {
      $error8 = "fill in phone";
      }
      if (empty($_POST["fname"]) ||
      empty($_POST["lname"]) ||
      empty($_POST["street"]) ||
      empty($_POST["city"]) ||
      empty($_POST["postcode"]) ||
      empty($_POST["country"]) ||
      empty($_POST["email"]) ||
      empty($_POST["phone"])) {
      } else {
      $form_items = $_POST;
      $document = new DOMDocument("1.0", "utf-8");
      if (is_file('form_data.xml'))
      {
      $document->load("form_data.xml");
      $xmlko = $document->getElementsByTagName('xml')->item(0);
      }
      else
      {
      $xmlko = $document->createElement("xml");
      $document->appendChild($xmlko);
      $xmlko = $document->getElementsByTagName('xml')->item(0);
      }
      $form = $document->createElement("form");
      $new_user = $document->createElement("user");
      foreach ($form_items as $ite => $val) {
      $this_user = $document->createElement($ite, $val);
      $new_user->appendChild($this_user);
      }
      $form->appendChild($new_user);
      $xmlko->appendChild($form);
      $document->save("form_data.xml");

      }
      }

      ?>


      Here is HTML code. Everything is in one PHP file.



      <!DOCTYPE html>
      <html>
      <head>
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <title>form</title>
      <link rel="stylesheet" href="CSS/styly.css">
      </head>
      <body>
      <h1>FORM</h1>
      <form action="" method="post">
      <p>FName:</p>
      <input type="text" name="fname"/><span class="error"><?php echo $error1?></span>
      <p>LName:</p>
      <input type="text" name="lname"/><span class="error"><?php echo $error2?></span>
      <p>Street:</p>
      <input type="text" name="street"/><span class="error"><?php echo $error3?></span>
      <p>City:</p>
      <input type="text" name="city"/><span class="error"><?php echo $error4?></span>
      <p>Postcode:</p>
      <input type="text" name="postcode"/><span class="error"><?php echo $error5?></span>
      <p>Country:</p>
      <input type="text" name="country"/><span class="error"><?php echo $error6?></span>
      <p>E-mail:</p>
      <input type="text" name="email"/><span class="error"><?php echo $error7?></span>
      <p>Phone:</p>
      <input type="text" name="phone"/><span class="error"><?php echo $error8?></span>
      <input type="submit" value="SUBMIT"/>
      </form>

      <?php

      $document = new DOMDocument("1.0", "utf-8");
      if (is_file('form_data.xml')) {
      $document->load("form_data.xml");
      $users = $document->getElementsByTagName("user");

      echo "<table>";

      echo '<tr>';
      foreach($users->item(0)->childNodes as $data) {
      echo '<th>'.$data->nodeName."</th>";
      }
      echo '</tr>';


      foreach($users as $user){
      echo '<tr>';
      foreach($user->childNodes as $data) {
      echo '<td>'.$data->nodeValue."</td>";
      }
      echo '</tr>';
      }

      echo "</table>";
      }

      ?>

      </body>
      </html>


      All data from the HTML form is inserted into the table below the form.
      Thanks in advance!







      php html validation form






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 11 '17 at 14:42









      Sᴀᴍ Onᴇᴌᴀ

      9,79162165




      9,79162165










      asked Nov 11 '17 at 8:56









      Tomas13TOTomas13TO

      213




      213






















          2 Answers
          2






          active

          oldest

          votes


















          5












          $begingroup$

          Instead of individual variables, you should use an array.



          $errors = [];
          foreach (['fname', 'lname', 'street'] as $field) {
          if (empty($_POST[$field])) {
          $errors[$field] = "$field must be filled in";
          }
          }

          if (!empty($errors)) {

          }


          And then, in the HTML:



          <?php echo $errors['fname'] ?>





          share|improve this answer









          $endgroup$





















            2












            $begingroup$

            @Roland Illig has a good point: the field names can be put into an array. Perhaps it would be best to use one array for the labels of the fields and then use that array to generate the field names.



            $fieldLabels = array("FName","LName","Street","City","Postcode","Country","E-mail","Phone");


            To get the field name (e.g. when iterating over each label), a function can be applied to the label. For the case of the labels above, the name can simply be derived by removing the hyphen (i.e. -) and making the label lowercase. For those operations, str_replace() and strtolower() can be used. This logic could be abstracted into a function (or method if a class was defined) and called when necessary:



            function GetFieldNameFromLabel($label) {
            return str_replace('-', '', strtolower($label));
            }


            Then when checking if all field have been completed, that function can be called. The labels can be iterated over, to check if there is a non-empty value in the POST data (i.e. $_POST) - if so, store such a value in an array (e.g. $validValues).



            $validValues = array();
            foreach($fieldLabels as $fieldLabel) {
            $fieldName = GetFieldNameFromLabel($fieldLabel);
            if (!empty($_POST[$fieldName])) {
            $validValues[$fieldName] = $_POST[$fieldName];
            }
            }


            Then the condition for adding the entry in the XML can simply be whether the number of values in that array of valid values is the same as the number of labels:



            if (count($validValues) == count($fieldLabels)) {
            //store values from $validValues in XML
            }


            Then for generating the form, the fields can be iterated over, and the error message can be added conditionally. One could even conditionally add the error message container (i.e. <span class="error">). Some may argue this logic should be separated from the HTML - that could be achieved using a template system (e.g. Smarty, Symfony Twig, etc.) - that could also be used for the display of existing data.



            <form action="" method="post">
            <?php
            foreach($fieldLabels as $fieldLabel) {
            $fieldName = GetFieldNameFromLabel($fieldLabel);
            $error = '';
            if ($_SERVER["REQUEST_METHOD"] == "POST" && !array_key_exists($fieldName, $validValues)) {
            $error = "Fill in ".$fieldName;
            }
            echo "<p>$fieldLabel:</p>";
            echo '<input type="text" name="'.$fieldName.'"/><span class="error">'.$error.'</span>';
            }





            share|improve this answer











            $endgroup$













              Your Answer





              StackExchange.ifUsing("editor", function () {
              return StackExchange.using("mathjaxEditing", function () {
              StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
              StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
              });
              });
              }, "mathjax-editing");

              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "196"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: false,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: null,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f180151%2fis-it-possible-to-make-this-php-code-shorter%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              5












              $begingroup$

              Instead of individual variables, you should use an array.



              $errors = [];
              foreach (['fname', 'lname', 'street'] as $field) {
              if (empty($_POST[$field])) {
              $errors[$field] = "$field must be filled in";
              }
              }

              if (!empty($errors)) {

              }


              And then, in the HTML:



              <?php echo $errors['fname'] ?>





              share|improve this answer









              $endgroup$


















                5












                $begingroup$

                Instead of individual variables, you should use an array.



                $errors = [];
                foreach (['fname', 'lname', 'street'] as $field) {
                if (empty($_POST[$field])) {
                $errors[$field] = "$field must be filled in";
                }
                }

                if (!empty($errors)) {

                }


                And then, in the HTML:



                <?php echo $errors['fname'] ?>





                share|improve this answer









                $endgroup$
















                  5












                  5








                  5





                  $begingroup$

                  Instead of individual variables, you should use an array.



                  $errors = [];
                  foreach (['fname', 'lname', 'street'] as $field) {
                  if (empty($_POST[$field])) {
                  $errors[$field] = "$field must be filled in";
                  }
                  }

                  if (!empty($errors)) {

                  }


                  And then, in the HTML:



                  <?php echo $errors['fname'] ?>





                  share|improve this answer









                  $endgroup$



                  Instead of individual variables, you should use an array.



                  $errors = [];
                  foreach (['fname', 'lname', 'street'] as $field) {
                  if (empty($_POST[$field])) {
                  $errors[$field] = "$field must be filled in";
                  }
                  }

                  if (!empty($errors)) {

                  }


                  And then, in the HTML:



                  <?php echo $errors['fname'] ?>






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 11 '17 at 10:21









                  Roland IlligRoland Illig

                  11.2k11844




                  11.2k11844

























                      2












                      $begingroup$

                      @Roland Illig has a good point: the field names can be put into an array. Perhaps it would be best to use one array for the labels of the fields and then use that array to generate the field names.



                      $fieldLabels = array("FName","LName","Street","City","Postcode","Country","E-mail","Phone");


                      To get the field name (e.g. when iterating over each label), a function can be applied to the label. For the case of the labels above, the name can simply be derived by removing the hyphen (i.e. -) and making the label lowercase. For those operations, str_replace() and strtolower() can be used. This logic could be abstracted into a function (or method if a class was defined) and called when necessary:



                      function GetFieldNameFromLabel($label) {
                      return str_replace('-', '', strtolower($label));
                      }


                      Then when checking if all field have been completed, that function can be called. The labels can be iterated over, to check if there is a non-empty value in the POST data (i.e. $_POST) - if so, store such a value in an array (e.g. $validValues).



                      $validValues = array();
                      foreach($fieldLabels as $fieldLabel) {
                      $fieldName = GetFieldNameFromLabel($fieldLabel);
                      if (!empty($_POST[$fieldName])) {
                      $validValues[$fieldName] = $_POST[$fieldName];
                      }
                      }


                      Then the condition for adding the entry in the XML can simply be whether the number of values in that array of valid values is the same as the number of labels:



                      if (count($validValues) == count($fieldLabels)) {
                      //store values from $validValues in XML
                      }


                      Then for generating the form, the fields can be iterated over, and the error message can be added conditionally. One could even conditionally add the error message container (i.e. <span class="error">). Some may argue this logic should be separated from the HTML - that could be achieved using a template system (e.g. Smarty, Symfony Twig, etc.) - that could also be used for the display of existing data.



                      <form action="" method="post">
                      <?php
                      foreach($fieldLabels as $fieldLabel) {
                      $fieldName = GetFieldNameFromLabel($fieldLabel);
                      $error = '';
                      if ($_SERVER["REQUEST_METHOD"] == "POST" && !array_key_exists($fieldName, $validValues)) {
                      $error = "Fill in ".$fieldName;
                      }
                      echo "<p>$fieldLabel:</p>";
                      echo '<input type="text" name="'.$fieldName.'"/><span class="error">'.$error.'</span>';
                      }





                      share|improve this answer











                      $endgroup$


















                        2












                        $begingroup$

                        @Roland Illig has a good point: the field names can be put into an array. Perhaps it would be best to use one array for the labels of the fields and then use that array to generate the field names.



                        $fieldLabels = array("FName","LName","Street","City","Postcode","Country","E-mail","Phone");


                        To get the field name (e.g. when iterating over each label), a function can be applied to the label. For the case of the labels above, the name can simply be derived by removing the hyphen (i.e. -) and making the label lowercase. For those operations, str_replace() and strtolower() can be used. This logic could be abstracted into a function (or method if a class was defined) and called when necessary:



                        function GetFieldNameFromLabel($label) {
                        return str_replace('-', '', strtolower($label));
                        }


                        Then when checking if all field have been completed, that function can be called. The labels can be iterated over, to check if there is a non-empty value in the POST data (i.e. $_POST) - if so, store such a value in an array (e.g. $validValues).



                        $validValues = array();
                        foreach($fieldLabels as $fieldLabel) {
                        $fieldName = GetFieldNameFromLabel($fieldLabel);
                        if (!empty($_POST[$fieldName])) {
                        $validValues[$fieldName] = $_POST[$fieldName];
                        }
                        }


                        Then the condition for adding the entry in the XML can simply be whether the number of values in that array of valid values is the same as the number of labels:



                        if (count($validValues) == count($fieldLabels)) {
                        //store values from $validValues in XML
                        }


                        Then for generating the form, the fields can be iterated over, and the error message can be added conditionally. One could even conditionally add the error message container (i.e. <span class="error">). Some may argue this logic should be separated from the HTML - that could be achieved using a template system (e.g. Smarty, Symfony Twig, etc.) - that could also be used for the display of existing data.



                        <form action="" method="post">
                        <?php
                        foreach($fieldLabels as $fieldLabel) {
                        $fieldName = GetFieldNameFromLabel($fieldLabel);
                        $error = '';
                        if ($_SERVER["REQUEST_METHOD"] == "POST" && !array_key_exists($fieldName, $validValues)) {
                        $error = "Fill in ".$fieldName;
                        }
                        echo "<p>$fieldLabel:</p>";
                        echo '<input type="text" name="'.$fieldName.'"/><span class="error">'.$error.'</span>';
                        }





                        share|improve this answer











                        $endgroup$
















                          2












                          2








                          2





                          $begingroup$

                          @Roland Illig has a good point: the field names can be put into an array. Perhaps it would be best to use one array for the labels of the fields and then use that array to generate the field names.



                          $fieldLabels = array("FName","LName","Street","City","Postcode","Country","E-mail","Phone");


                          To get the field name (e.g. when iterating over each label), a function can be applied to the label. For the case of the labels above, the name can simply be derived by removing the hyphen (i.e. -) and making the label lowercase. For those operations, str_replace() and strtolower() can be used. This logic could be abstracted into a function (or method if a class was defined) and called when necessary:



                          function GetFieldNameFromLabel($label) {
                          return str_replace('-', '', strtolower($label));
                          }


                          Then when checking if all field have been completed, that function can be called. The labels can be iterated over, to check if there is a non-empty value in the POST data (i.e. $_POST) - if so, store such a value in an array (e.g. $validValues).



                          $validValues = array();
                          foreach($fieldLabels as $fieldLabel) {
                          $fieldName = GetFieldNameFromLabel($fieldLabel);
                          if (!empty($_POST[$fieldName])) {
                          $validValues[$fieldName] = $_POST[$fieldName];
                          }
                          }


                          Then the condition for adding the entry in the XML can simply be whether the number of values in that array of valid values is the same as the number of labels:



                          if (count($validValues) == count($fieldLabels)) {
                          //store values from $validValues in XML
                          }


                          Then for generating the form, the fields can be iterated over, and the error message can be added conditionally. One could even conditionally add the error message container (i.e. <span class="error">). Some may argue this logic should be separated from the HTML - that could be achieved using a template system (e.g. Smarty, Symfony Twig, etc.) - that could also be used for the display of existing data.



                          <form action="" method="post">
                          <?php
                          foreach($fieldLabels as $fieldLabel) {
                          $fieldName = GetFieldNameFromLabel($fieldLabel);
                          $error = '';
                          if ($_SERVER["REQUEST_METHOD"] == "POST" && !array_key_exists($fieldName, $validValues)) {
                          $error = "Fill in ".$fieldName;
                          }
                          echo "<p>$fieldLabel:</p>";
                          echo '<input type="text" name="'.$fieldName.'"/><span class="error">'.$error.'</span>';
                          }





                          share|improve this answer











                          $endgroup$



                          @Roland Illig has a good point: the field names can be put into an array. Perhaps it would be best to use one array for the labels of the fields and then use that array to generate the field names.



                          $fieldLabels = array("FName","LName","Street","City","Postcode","Country","E-mail","Phone");


                          To get the field name (e.g. when iterating over each label), a function can be applied to the label. For the case of the labels above, the name can simply be derived by removing the hyphen (i.e. -) and making the label lowercase. For those operations, str_replace() and strtolower() can be used. This logic could be abstracted into a function (or method if a class was defined) and called when necessary:



                          function GetFieldNameFromLabel($label) {
                          return str_replace('-', '', strtolower($label));
                          }


                          Then when checking if all field have been completed, that function can be called. The labels can be iterated over, to check if there is a non-empty value in the POST data (i.e. $_POST) - if so, store such a value in an array (e.g. $validValues).



                          $validValues = array();
                          foreach($fieldLabels as $fieldLabel) {
                          $fieldName = GetFieldNameFromLabel($fieldLabel);
                          if (!empty($_POST[$fieldName])) {
                          $validValues[$fieldName] = $_POST[$fieldName];
                          }
                          }


                          Then the condition for adding the entry in the XML can simply be whether the number of values in that array of valid values is the same as the number of labels:



                          if (count($validValues) == count($fieldLabels)) {
                          //store values from $validValues in XML
                          }


                          Then for generating the form, the fields can be iterated over, and the error message can be added conditionally. One could even conditionally add the error message container (i.e. <span class="error">). Some may argue this logic should be separated from the HTML - that could be achieved using a template system (e.g. Smarty, Symfony Twig, etc.) - that could also be used for the display of existing data.



                          <form action="" method="post">
                          <?php
                          foreach($fieldLabels as $fieldLabel) {
                          $fieldName = GetFieldNameFromLabel($fieldLabel);
                          $error = '';
                          if ($_SERVER["REQUEST_METHOD"] == "POST" && !array_key_exists($fieldName, $validValues)) {
                          $error = "Fill in ".$fieldName;
                          }
                          echo "<p>$fieldLabel:</p>";
                          echo '<input type="text" name="'.$fieldName.'"/><span class="error">'.$error.'</span>';
                          }






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited 8 mins ago

























                          answered Nov 11 '17 at 13:25









                          Sᴀᴍ OnᴇᴌᴀSᴀᴍ Onᴇᴌᴀ

                          9,79162165




                          9,79162165






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Code Review Stack Exchange!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              Use MathJax to format equations. MathJax reference.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f180151%2fis-it-possible-to-make-this-php-code-shorter%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              is 'sed' thread safeWhat should someone know about using Python scripts in the shell?Nexenta bash script uses...

                              How do i solve the “ No module named 'mlxtend' ” issue on Jupyter?

                              Pilgersdorf Inhaltsverzeichnis Geografie | Geschichte | Bevölkerungsentwicklung | Politik | Kultur...