I have the following piece of code and inside the function field_has_input(), I would like to assign the element’s key to the errors[]
i.e. errors[]=$key instead of errors[]=$field
The function field_has_input($field) gets called from check_all_fields($_POST)
Hopefully someone can help out.
function field_has_input($field)
{
global $errors;
if(!isset($field) || empty($field))
{
$errors[]=$field;
}
}
function check_all_fields($_POST)
{
global $errors;
foreach($_POST as $key => $value)
{
echo $_POST[$key] . "<br />";
field_has_input($_POST[$key]);
}
//exit;
var_dump($errors);
return $errors;
}
I would suggest you dispense with the
field_has_input()function entirely, and just do the work inside the other loop. Otherwise, you would need to be passing the$keyinto the inner function. In its current simplicity it is totally unnecessary and adds complexity.Further, I would recommend not using the
globalerrors, but instead passing it to the function. Because$_POSTis a superglobal, it is unnecessary to pass it as a parameter to your function. Pass only$errorsinstead.If you must use an inner function, such as if the actual work to be done in
field_has_input()is more complex than just checkingempty(), pass the$keyand check$_POST[$key]inside the function