With foreach
, you don't have to know the names of the keys in the array.
foreach($_POST as $key => $field) {
isvalid($field);
}
$key
contains the names like "field1", "field2" and so on while $field
contains the value inside the $_POST
array. The foreach loop will then run the function invalid()
on each of the field value.
To check if the field values are set:
// Sample $_POST array
$_POST = array(
"field1" => "", // this is not set
"field2" => "data"
);
foreach($_POST as $key => $field) {
// You can check if it is empty using foreach alone
if (strlen($field) > 0) {
// this field is set
} else {
// this field is not set
}
}
You can use empty()
as well but it treats "0"
as empty so be careful.