views:

75

answers:

3

Hello all, how can I prevent PHP from returning an Undefined variable error every time I try to check a variable if it has contents and that certain variable hasn't been used yet? In my previous setup, I can check $_POST['email'] even if I haven't put anything into it yet. It simply returns a blank or empty result. That's how I want my PHP setup to work but for the life of me, I can't seem to find figure out how to configure it. :(

Example:

<?php
if ($_POST['info'] != '') {
  // do some stuff
}
?>
<form method="post">
<input type="text" name="info" />
<input type="submit" />
</form>

When you use the above script in a single PHP page and run it on my current setup, it returns an Undefined variable error. On my previous setup, that script worked like a charm. Can anyone share some light into this problem of mine. If you need further details, just say so and I will try to add more details to this post.

I know about the isset() checking but I don't want to use it on all of my scripts. I want it to not be that restrictive about variables.

A: 

The only way to do is to abuse the error reporting directive. Using it, you can disable warnings for undefined variables, but that's all it does.

Is using isset() really too hard for you? It is the only correct way to do it. Not using isset is the same as writing shit code. Do you want to write shit code?

(Yes, snarky tone on purpose ;) )

Jani Hartikainen
How do I go about "abusing" the error reporting directive? I'm quite not fond of PHP's configuration and such. And I just want to be able to quickly test scripts.
Shedo Chung-Hee Surashu
-1. This is not "the only way" — see e.g. the `empty` function.
You
+1  A: 

Most likely it's not an error, but a Warning. You can set PHP not to display errors/warnings if you want. Just add this to the begining of your code:

ini_set('display_errors', 0);

Altough, I recommend you not to be lazy and have your code not display any errors, warnings, notices whatsoever, better safe than sorry.

And the preferred way to do what you want to do is

<?php
if (isset($_POST['info'])) {
  // do some stuff
}
?>
<form method="post">
<input type="text" name="info" />
<input type="submit" />
</form>
Claudiu
Or actually check if you're handling a POST: `if ($_SERVER['REQUEST_METHOD'] == 'POST') { ... }`
Marc B
+1  A: 

You could use the empty function, which returns true if the variable is either unset or empty (i.e. a zero-length string, 0, NULL, FALSE and so on):

if(!empty($_POST['variable'])){
    /* ... */
}

This is pretty much the same test as the one you're doing now, except that it will also return false (not run the block), without warnings, when the variable is unset.

You