Horizon88 wrote:Note that this is similar to etully's, but if the form field actually isn't set, his example would throw a PHP warning of an undefined index. By first checking that it is set before checking the empty, we prevent throwing the warning.
This is not entirely true. [man]empty/man does an internal [man]isset/man first before seeing if it's empty. So utilizing [man]empty/man in the way etully does would not raise any php errors. Don't believe me? Try this code:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL | E_STRICT); // Set all error options
$var = array(); // An empty array
// This should totally not exist!
$empty = empty($var['nested']['level']['of']['some']['number']['of']['random']['levels']);
var_dump($empty);
// and to raise the error...
echo $empty['nested']['level']['of']['some']['number']['of']['random']['levels'];
From that simple test-case, you can see the var_dump() resulting in boolean true without any errors; however, the echo raises the undefined index error 😉
Another point to make is that [man]empty/man will associated 0, false, and a string length of 0 to be empty. So if you have an integer field which someone inputs 0 but the input is required, empty() will return true (since 0 is empty). Thus when validating inputs, it's best to do a dual test: [man]isset/man and [man]strlen/man.
<?php
if(isset($_POST['some_item']) && strlen($_POST['some_item']) > 0)
{
// Do something
}
You could extrapolate that into your own unique function like:
<?php
function hasvalue($var)
{
return (isset($var) && strlen($var) > 0);
// Or more concisely
return (isset($var) && strlen($var));
}
You could even make it throw up your own error messages:
function hasvalue($var)
{
if(!isset($var))
{
trigger_error($var.' does not exist!', E_USER_NOTICE);
return false;
}
if(strlen($var) < 1)
{
trigger_error($var.' is empty!', E_USER_NOTICE);
return false;
}
// If we're here, it's set and it has a positive length
return true;
}
Hope that helps clarify things.