3

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

  1. First want to find which type of variable $mo is ?(string or integer or other)

  2. 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

1
  • 1
    As a side note, you are using == which tests for equality, such as 1 == '1' which would evaluate to true. But when you use === it tests if the types are equal. In my example 1 === '1' will return false, since int is not a String. Commented Feb 4, 2010 at 16:59

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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
}

Comments

3

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
 }

2 Comments

if (!isset($mo) || empty($mo)) is redundant. if (empty($mo)) has the same behavior.
Problem with "empty($var)" function is that consider $var="0" as ... empty. Which is obviously not ...
0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.