php : How to check a field have blank/empty/NULL value?
I want to display an error when a variable have a BLANK value or EMPTY or NULL value. for example variable is shown below:
$mo = strtotime($_POST['MondayOpen']);
and
var_dump($_POST['MondayOpen'])
returns string(0) "".
Now I go with below approach
First want to find which type of variable
$mo
is ?(string or integer or other)Which function is better to find that
$mo
having no value.
I conduct a test with $mo
开发者_运维知识库 and got these results
is_int($mo);//--Return nothing
is_string($mo); //--Return bool(false)
var_dump($mo); //--Return bool(true)
var_dump(empty($mo));//--Return bool(true)
var_dump($mo==NULL);//--Return bool(true)
var_dump($mo=='');//--Return nothing
Please suggest an optimum and right approach to check the variable integrity
var_dump outputs variables for debugging purposes, it is not used to check the value in a normal code. PHP is loosely typed, most of the time it does not matter if your variable is a string or an int although you can cast it if you need to make sure it is one, or use the is_ functions to check.
To test if something is empty:
if ( empty( $mo ) ) {
// error
}
empty() returns true if a variable is 0, null, false or an empty string.
doing strtotime will return false if it cannot convert to a time stamp.
$mo = strtotime($_POST['MondayOpen']);
if ($mo !== false)
{
//valid date was passed in and $mo is type int
}
else
{
//invalid date let the user know
}
PHP offers a function isset
to check if a variable is not NULL
and empty
to check if a variable is empty.
To return the type, you can use the PHP function gettype
if (!isset($mo) || is_empty($mo)) {
// $mo is either NULL or empty.
// display error message
}
You can check its type using:
gettype($mo);
but null and empty are different things, you can check with these functions:
if (empty($mo))
{
// it is empty
}
if (is_null($mo))
{
// it is null
}
Another way to check if variable has been set is to use the isset construct.
if (isset($mo))
{
// variable has been set
}
精彩评论