Home » Php » Empty variable define in php

Empty variable define in php

Posted by: admin April 23, 2020 Leave a comment


Before doing something with $error:

$error = NULL;

In some script’s saw:

$error = '';
$error = false;
$error = 0;
  • Which method is ‘better’ or maybe it depends in which situation i use
    it ?
  • What’s your suggestion ?
How to&Answers:

Depends on your design:

  • Are you setting it as an Object in case of error? Use NULL.
  • Are you setting it to true in case of error? Use false.
  • Are you setting it as a number of some sort in case of error? Use 0.
  • Are you setting it to a string to describe the error? Use ''.

A better way to indicate errors would be throwing Exceptions though, rather than setting a variable and determine the error according to it.


There is no canonical answer to this question. As long as you use one of these semaphores consistently, you can use anything you want. Because PHP is loosely-typed, all of these values are “falsy” and can be evaluated in a boolean comparison as FALSE.

That said, there is more of a difference between the empty string and the others, so I’d stick with NULLs and FALSEs in this sort of scenario.



$v = NULL;

settype($v, 'string');
settype($v, 'int');
settype($v, 'float');
settype($v, 'bool');
settype($v, 'array');



$v = NULL;
var_dump( (string) $v);
var_dump( (int) $v);
var_dump( (float) $v);
var_dump( (bool) $v);
var_dump( (array) $v);


It depends upon the conditions where you need to use the $error. Using a NULL is what I chose mostly as I deal more with MySQL clauses and all!