Page 1 of 1

How to validate forms in an array?

Posted: Sat Aug 21, 2010 7:16 am
by Bbob
Hi

How do I validate multiple forms in an array?

I know the first step is to store forms in an array.

Code: Select all

$array = array($_POST['name'], $_POST['age'], $_POST['date'],$_POST['number']);
Next step is to loop

This is where Im lost :lol:

How do i cycle through the array checking for an empty value, then take whatever form the empty value is and display it?

Re: How to validate forms in an array?

Posted: Sat Aug 21, 2010 8:33 am
by oscardog
Not quite sure I understand exactly what you want but the easiest way would be to do the following:

Code: Select all

foreach($_POST as $key => $value) {
//Do your validation for each input here, for example check if the field is empty or not
if(strlen(trim($value)) == 0) {
//Field is empty
}
}
Inside the loop you $key is the fieldname and $value is the value in that field.

Re: How to validate forms in an array?

Posted: Sat Aug 21, 2010 12:33 pm
by AbraCadaver
I'm not quite sure either, but this will display the empty fields (be aware that 0 is empty as well and you may not want that):

Code: Select all

echo 'The fields '.implode(', ', array_keys(array_diff_assoc($_POST, array_filter(array_map('trim', $_POST))))).' are empty!';