Im wondering if there is a shorter way to write this?
It's not so much a shorter way, but considering all things, not as efficient as it could be in terms of what you need to do. Aside from the suggestions above, checking if it's set is only part of the equation. You also want to make sure it's the data type you expect.
Additionally, you can be a little more "friendly" with your messages, and instead of testing for a "not" value, if you expect a value, test for it and only return an error value you don't get what you expect. Example,
// If anything NOT these characters is found,
// throw an error. We expect record_id to be digits,
// name to be letters, spaces, and ' only - note this
// is a BIG PROBLEM for international names with
// special characters, posted here for example only.
$input_vals = Array (
'record_id' => '\d',
'your_name' => 'a-z\d\s\''
);
$errors = check_data($_POST,$input_vals);
if ($errors) {
echo "<p>The form could not be processed due to the following errors:</p><ul>
$errors</ul>";
}
else {
// carry on
}
function check_data($input,$expected) {
$err = null;
foreach ($expected as $key=>$regex) {
if (! isset($input[$key]) or (isset($input[$key]) and preg_match("/[^$regex]+/i",$input[$key]))) {
$err .= "<li>The $key value was not input or is an invalid value.</li>";
}
}
return $err;
}
So now you've done several things that combine many of your tasks:
- Checked isset
- checked proper data type
- maximized usage of your data test to return a more appropriate value, one you can use as opposed to true/false, moving any actions you'd take on true/false into your data check
- begun to move toward a more comprehensive experience to the end user with a "friendly" message
- by making the code a little longer, you've condensed the overall code base because you've combined multiple tasks in what was a single task
Of course, this is a simplified example, and you wouldn't want to say "record_id," perhaps a more robust hashing and array would be a better idea, but this gets you thinking about two concepts,
accept only what you want and discard everything else, and thinking forward to the overall total task, not just a micro piece of it.