Kevin
Kevin

Reputation: 289

PHP. What is the best way to initialize a variable, FALSE, NULL, 0 OR ''?

Taking into account boolean, strings and integers. What is the best all purpose way to initialize a variable that is going to cause the least amount of problems.

Upvotes: 0

Views: 7230

Answers (2)

Ch Hamza Javed
Ch Hamza Javed

Reputation: 330

TRUE/FALSE, only use if you want to declare a Boolean variable, like if you want to check if a variable has something then declare another variable with bool

$var = "hello";
if ($var == "hello") {
    $new_var = TRUE;
} else {
    $new_var = FALSE;
}

NULL variable is use when you want to check if some variable is NULL or not

$var = NULL;
if ($var != NULL 
{ echo "something"; }

sometimes a variable can have value 0 so we cannot check for the empty variable if we assigned it a 0 value

$var = 0;
if ($var != 0)
{ echo "something"; }

'' is mostly used to initialize a variable so that if i want to check whether a variable is empty or not and works for string or integer etc

$var = '';
if ($var != '')
{ echo "something"; }

Upvotes: 1

Abhay Maurya
Abhay Maurya

Reputation: 12277

It depends if you know where you are going to use the variable. What its data type is going to be.

For instance, array variables: $test = [];

If you don't know exactly for what you are going to use the variable then i advise to don't initialize it at all. In my experience, i never met the scenario where I had to necessary initialize a variable if I wasnt sure whats its nature gonna be.

We do need arrays to be initialized sometimes and for that i gave the example of initializing empty array.

Although initializing a variable with NULL might not serve your purpose if you are planning to use isset() function later on for some reason, and for rest options you mentioned, empty() function will always return true for them so maybe clear your question a bit to exactly what scenario you are talking for.

Upvotes: 1

Related Questions