The problem with code like this:
$var = $_POST[var]; // From a form
is that if the specified index of the $_POST array doesn't exist, you're running into the E_NOTICE error I mentioned above. That's why I write such code like so:
$var = (isset($_POST['var']) ? $_POST['var'] : '');
Otherwise, you might do something like:
if(!empty($_POST['submit'])) {
// know that $_POST['submit'] exists, process form data
}
Again, using [man]empty/man avoids the E_NOTICE error because it is a function specifically designed for this situation.
Channel5 wrote:Also, what's the difference between, for example, $POST['var'] and $POST[var]?
Simple; the latter of the two isn't entirely correct. :p Array indexes in arrays like:
$_POST = array('var' => 'value');
are strings. In PHP, all strings are denoted by some form of an identifier, be it single quotes, double quotes, or a heredoc/nowdoc syntax.
The absence of quotations in $_POST[var] as you have it would suggest that var is a constant (see: [man]constants[/man] if you don't know what these are). In the case where no such constant is defined, PHP will throw an E_NOTICE error - "Use of undefined constant ..." and assume that you meant the index to be a string.
Depending upon the name, however, you can either cause parse errors or experience odd behavior. Some examples:
echo $_POST[var]; // parse error; 'var' has special meaning when not in a string
define('foo', 'FOO BAR');
$_POST['foo'] = 'Hello world!';
echo $_POST[foo]; // PHP error: Notice: Undefined index: FOO BAR
EDIT: Note that variable interpolation in a [man]string[/man] has different rules. The following two lines are correct ways to reference an array index inside a string:
echo "Hello $_POST[foo]!";
echo "Hello {$_POST['foo']}!";