Processing POST values

I am wanting to ascertain if certain POST variables are set by referring to them in a variable called $varname.

So if I want to check to see if the ‘courseid’ variable has been set I would like to do it like this.

$varname = ‘courseid’;

if(!isset($_POST[‘$varname’])) {
// do something
// error occured

This does not work. What do I need to do to make it work or is there a better way?

I have tried using the eval function despite being warned against it but it still does not work.

Thanks for any help you can give me.


Wouldn’t you just remove the quotation marks?

if (!isset($_POST[$varname])) {

My code for this would be something like

$courseid = $POST[‘courseid’];

if(!isset($courseid)) {

} else {


Also do not forget to validate the post values before processing them in a database, this code also assumes that you have a form field with the name courseid

Hi Justin

A few tips, as droopsnoot said, if you use $_POST[‘$varname’] then because you have single quotes around the variable, you are actually saying “please return me the value of the $_POST array where the key is the string $varname” where as if you remove the single quotes, you are saying “please return me the value of the $_POST array where the key is the string courseid”.

While we are on the topic, if you had used $_POST[“$varname”] (note the double quote marks), then it would have worked the same as $_POST[$varname]. This is because php checks strings defined with double quotes for any variable values. Personally I try to avoid double quotes, because they are too easy to accidentally create a security hole.

Also, I thought I should mention that your logic might not quite work how you thought. !isset($_POST[$varname]) says “if the variable isn’t set” and isset($_POST[$varname]) says “if the variable is set” because the ! character says “reverse the logical outcome (turn false to true, and true to false)”. So:

$varname = 'courseid';
if (isset($_POST[$varname])) {
  // $_POST[$varname] is set as something, do something with it
} else {
  // $_POST[$varname] is [B]not[/B] set as something, error?

Thanks for all of the replies. I removed the single quotes and it worked fine.

What I am doing is setting up an array populated with expected inputs from a form including validation information so that the
processing code is generic and does not need to be repeated for each form.

It is going well so far but so much to lean about php!!