kaspnord
kaspnord

Reputation: 1483

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

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.

Upvotes: 29

Views: 52318

Answers (4)

stamster
stamster

Reputation: 981

chr(32) represents ASCII space (i.e. string of 1 byte length).

If you want to avoid mistakes like $myEmpty = " " vs. $myEmpty = " " vs. $myEmpty = ""

Sometimes it's hard to tell when there are two spaces or one or none by human eyes. Using chr function that is solved for sure.

And for really empty string (zero bytes), there's no other way but to simply define it with (single) quotation marks like $nothing = '';

Upvotes: 0

Conrad Shultz
Conrad Shultz

Reputation: 8808

For the most part this is irrelevant. Unlike many languages, in PHP it (usually) doesn't matter whether you initialize a variable. PHP will automatically cast an uninitialized (or even undeclared) variable as appropriate for the immediate use. For example, the following are all correct:

$a;
$a + 7; // Evaluates to 7
$a . "This is a test."; // Evaluates to "This is a test."
if (! $a) {}  // Evaluates as true

The one caveat is that select functions check for variable type (as does strict equality checking, ===). For example, the following fails:

$a;
if (is_string($a)) {
    print 'success';
}
else {
    print 'fail';
}

This convenience comes at a heavy cost, though. Unlike strictly typed (or, at least, "more strictly" typed) languages, there is nothing in the core language itself to help you catch common programmer errors. For example, the following will happily execute, but probably not as expected:

$isLoggedIn = getLoginStatus($user);
if ($isLogedIn) {
    // Will never run
    showOrder($user);
}
else {
    showLoginForm();
}

If you choose to initialize all your variables, do it just as you did. But then enable PHP notices (E_NOTICE) to get run-time warnings about uninitialized variables. If you don't, you're basically wasting time and keystrokes initializing your own variable.

Upvotes: 7

Mike Purcell
Mike Purcell

Reputation: 19999

Here are some other things to consider when working with strings in PHP:

// Localize based of possible existence
$account = (array_key_exists('account', $results)) ? $results['account'] : null;

// Check to see if string was actually initialized
return (isset($account)) ? $account : null

// If a function is passed an arg which is REQUIRED then validate it
if (empty($arg1)) {
    throw new Exception('Invalid $arg1');
}

echo $arg;

// If you are looking to append to string, then initialize it as you described
$account = null;

if (!empty($firstName)) {
    $account .= $firstName;
}

echo $account;

// Also, it's better to initialize as null, so you an do simple check constructs
if (is_null($account)) {
    // Do something
}

// Versus these types of checks
if ($account == '') {
    // Do something
} 

Normally I try to avoid initializing vars like this. Instead I localize, or check for existence throughout the code, otherwise you end up maintaining a laundry list of variables which may not actually reflect usage throughout the code following initialization.

Upvotes: 3

No Results Found
No Results Found

Reputation: 102844

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.

Upvotes: 38

Related Questions