29

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.

1
  • 3
    Strings aren't first class objects in php, so there's not really any other way to initialize them in your code ... Commented Jan 27, 2012 at 17:20

4 Answers 4

38

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.

Sign up to request clarification or add additional context in comments.

3 Comments

What about: $account = null; ?
Yeah, that will work fine. It's all context dependent, you may want to see if the value is NULL instead of "" (empty string) later (but really you shouldn't need to). Your method is much clearer, you can tell the var is a string right away. Weak typing can be your friend or enemy.
I was searching for something today for my syntax highlighter, I've used both single and double quotes in javascript side, and I need to output an empty string from PHP, something like {{ $var ? $var : "" }}, but the highlighter won't allow me to see some pretty code, even if it's completely valid. null would be better in cases like this. Thanks for the heads up @WesleyMurch.
7

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.

Comments

3

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.

Comments

0

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 = '';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.