Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to initialize empty strings in PHP?

Tags:

In C#, I've come to adopt the following method of initializing empty strings:

string account = string.empty; 

rather than

string account = ""; 

According to my mentor and other C# developers I've talked to, the first method is the better practice.

That said, is there a better way to initialize empty strings in PHP? Currently, I see the following widely used:

$account = ''; 

Thanks.

like image 441
kaspnord Avatar asked Jan 27 '12 17:01

kaspnord


People also ask

What is empty string in PHP?

The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true. The following values evaluates to empty: 0. 0.0.

How do you set an empty string?

An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .

Is empty string null in 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 .


1 Answers

What you're doing is correct. Not much more to say about it.

Example:

$account = '';  if ($condition)  $account .= 'Some text';  echo  $account; 

You could get silly and do something like this:

$str = (string) NULL; 

..but that's utterly pointless, and it's exactly the same thing - an empty string.

You're doing it right.

like image 199
Wesley Murch Avatar answered Sep 20 '22 13:09

Wesley Murch