I have a form where users can enter the names and emails addresses of colleagues. They are not required to enter anything. However if a name is entered then the email address is required.
<form>
1st name <input type="text" name="name_1" value"" />
1st email <input type="text" name="email_1" value"" />
2nd name <input type="text" name="name_2" value""/>
2nd email <input type="text" name="email_2" value""/>
</form>
I can already make certain fields required using the function below. I think I could use an if else statement to check if the 1st name had a value then make the 1st email required. However the form has twenty potential name / email pairs.
What i'm after is advice about the sort of thing I should be trying to do this rather than a complete solution. I appriciate this a bit of a vague question but I'm very new to PHP and am having difficulty searching for a solution.
function check_required_fields($required_array) {
$field_errors = array();
foreach($required_array as $fieldname) {
if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && !is_numeric($_POST[$fieldname]))) {
$field_errors[] = $fieldname;
}
}
return $field_errors;
}