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

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


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.


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.


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 initializedreturn (isset($account)) ? $account : null// If a function is passed an arg which is REQUIRED then validate itif (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 constructsif (is_null($account)) {    // Do something}// Versus these types of checksif ($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.