How to validate forms in an array?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Bbob
Forum Commoner
Posts: 57
Joined: Sat Aug 07, 2010 4:46 am

How to validate forms in an array?

Post 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?
oscardog
Forum Contributor
Posts: 245
Joined: Thu Oct 23, 2008 4:43 pm

Re: How to validate forms in an array?

Post 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.
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: How to validate forms in an array?

Post 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!';
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply