ユーザー定義関数があります。フォームの必須フィールドの配列として 1 つの引数を取ります。これらのフィールドが空かどうかをチェックします。それらが空の場合、メッセージを返し、フォームの処理を停止します。
<?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>
フォームの必須フィールドが入力されている場合でも、関数はこのエラーを返していますか? これを修正するには?名前の前に echo という単語を書かずに関数を使用するにはどうすればよいですか?
この関数を使用したいので、フォーム内のすべてのフィールドに対して if および else ステートメントを手動で記述する必要はありません。