Asperger
Asperger

Reputation: 3222

Foreach loop that loops through $_POST data instead of static isset($_POST["name"]......)

So here I am again trying to find better ways of doing things. 90% of tutorials do things the normal way below:

if (isset($_POST['name']) && isset($_POST['password'])) {
     // Does some stuff...
    }

It is fine but it does seem too static since I prefer something far more dynamic. For example lets say looping through all $_POST arrays within a contact form. This way I can change the name or the fields to whatever I want or add more...my code will always handle the rest.

I know a foreach loop would come in handy but, as someone new to the world of programming and php I thought you could show me how something like this is done. So how do I replace the above with a for loop? I am not sure where to start.

Upvotes: 1

Views: 723

Answers (3)

Danyal Sandeelo
Danyal Sandeelo

Reputation: 12401

try this:

$check=true;   
if(isset($_POST)){
  foreach($_POST as $key=>$value){
   if(!isset($_POST[$key]){
    $check = false;
    break;
     } 
  }
}

based on $check you can verify if it was properly sent or not.

Another approach is to have a sort of verification because it is possible you might not get the key in $_POST

$keys =array("input1","input2");

$check=true;   
if(isset($_POST)){
  foreach($keys as $input){
   if(!array_key_exists($input,$_POST)){
    $check = false;
    break;
     } 
  }
}

Upvotes: 2

Daimos
Daimos

Reputation: 1473

You can always use foreach loop like that:

foreach($_POST as $key => $value){ echo '$_POST["'.$key.'"] = "'.$value.'"'}

But remember, that anyone, can modify your form, prepare some post statement and send data that can create little mess with your code. So it`s good way to validate all fields. Dynamic validation is of course possible, but you need to do it right!

Upvotes: 0

Akshay
Akshay

Reputation: 2229

Well you could try something like this :-

<?php
$inputNames = array("input1","input2");
foreach($inputNames as $input)
{
    if (isset($_POST["$input"]) && isset($_POST["$input"])) {
     // Does some stuff...
    }
}
?>

Make an array with the names of all your input tags, and then simply do a foreach between them. In this way, you always only need to edit the names array.

Upvotes: 0

Related Questions