Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty variable define in php

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 ?
like image 539
ZeroSuf3r Avatar asked Mar 18 '12 17:03

ZeroSuf3r


People also ask

What is an empty variable?

A variable is considered empty if it does not exist or if its value equals FALSE .

Is null or empty PHP?

is_null() The empty() function returns true if the value of a variable evaluates to false . This could mean the empty string, NULL , the integer 0 , or an array with no elements. On the other hand, is_null() will return true only if the variable has the value NULL .

What is a null variable in PHP?

In PHP, a variable with no value is said to be of null data type. Such a variable has a value defined as NULL. A variable can be explicitly assigned NULL or its value been set to null by using unset() function.


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

like image 151
Madara's Ghost Avatar answered Oct 19 '22 01:10

Madara's Ghost


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.

like image 44
Interrobang Avatar answered Oct 19 '22 03:10

Interrobang


1.

$v = NULL;

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

var_dump($v);

2.

$v = NULL;
var_dump( (string) $v);
var_dump( (int) $v);
var_dump( (float) $v);
var_dump( (bool) $v);
var_dump( (array) $v);
like image 4
Loading Avatar answered Oct 19 '22 02:10

Loading


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!

like image 1
hjpotter92 Avatar answered Oct 19 '22 01:10

hjpotter92