Php: How to check a field has an empty / empty / null value?

I want to show an error when the variable is BLANK or EMPTY or NULL. for example, the variable is shown below:

 $mo = strtotime($_POST['MondayOpen']);

and
  var_dump($_POST['MondayOpen'])returnsstring(0) "".

Now i'm coming with the approach

  • First you need to find what type of variable $mois there? (string or integer or other)

  • Which function is better to find if it $modoes not matter.

I did a test with $moand 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 optimal and correct approach for checking the integrity of a variable

+3
source share
4 answers

running strtotime will return false if it cannot convert to a timestamp.

$mo = strtotime($_POST['MondayOpen']);
if ($mo !== false)
{
//valid date was passed in  and $mo is type int
}
else
{
//invalid date let the user know
}
+3
source

var_dump , . PHP , , int, , , , is_ .

, - :

if ( empty( $mo ) ) {
  // error
}

empty() true, 0, null, false .

+4

PHP isset, , NULL empty, , .

, PHP gettype

if (!isset($mo) || is_empty($mo)) {
 // $mo is either NULL or empty.
 // display error message
 }
+3

, :

gettype($mo);

null empty - , :

if (empty($mo))
{
  // it is empty
}

if (is_null($mo))
{
  // it is null
}

Another way to check if a variable has been set is to use the isset construct .

if (isset($mo))
{
  // variable has been set
}
0
source

Source: https://habr.com/ru/post/1731419/


All Articles