I am creating a contact form in PHP. On the PHP script I am using to process the email, I am defining variables based on the submitted form fields. All of these form fields are required, so they will always exist. Currently I am setting the variables like this:
$fName = $_POST['first-name'];
This works fine, but if I have error reporting turned on, I end up getting Notice: Undefined index: first-name
If I set up the variable like this, I don't get the undefined index:
if (isset($_POST['first-name'])) {
$fName = $_POST['first-name'];
}
But it doesn't feel right to do this because I'm basically adding 2 lines of code for every input. Is this the only way to avoid the Undefined index
error? What is the correct way to define these variables, especially knowing that they are all required fields, so they will always be "set?"
But it doesn't feel right...
Yup, A man's gotta do what a man's gotta do.
All you can do is simplify it as
$fName = isset($_POST['first-name'])? $_POST['first-name'] : '';
If you are using PHP > 7.x.x
, you can use the null coalescing operator which will provide the same result as above and was build specifically keeping this scenario in mind.
So I say this wins in terms of usability. Thanks @Cid for mentioning this.
$fname = $_POST['first-name'] ?? '';