0

I have a user defined function, it takes one argument as an array for the form required fields. It checks if these fields are empty or not. If they are empty it will return a message and stop processing the form.

<?php

function check_required_fields($required_array) {
    foreach($required_array as $fieldname) {
        if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) { 

        }
    }
    return "You have errors";
}
$required_array = array('name', 'age');
if (isset($_POST['submit'])) {
    echo check_required_fields($required_array);
}
?>

<html>
<body>

<form action="#" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit" name="submit">
</form>

</body>
</html>

The function is returning this error even when the form required fields are filled? how to fix this? How can i use just use the function with out writing the word echo before its name?

I want to use this function so i don't have to manually write the if and else statement for every field in the form.

4

1 回答 1

1

我想你想这样做吗?

function check_required_fields($required_array) {
    foreach($required_array as $fieldname) {
        if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) { 
            return "You have errors"; //This indicates that there are errors
        }
    }
}

或者为什么不只是:

function check_required_fields($required_array) {
    foreach($required_array as $fieldname) {
        if (!isset($_POST[$fieldname])) { 
            return "You have errors"; //This indicates that there are errors
        }
    }
}

更新:

改变:

$required_array = array('name', 'age'); //This just sets strings name and age into the array

至:

$required_array = array($_POST['name'], $_POST['age']); //This takes the values from the form
于 2013-09-08T10:15:30.203 回答