1

I usually set all my variables, even if they might not return anything. But now I wonder:

What harm will it make if I echo an empty variable?

eg.

<?php

$a = 'a';
$b = 'b';

if($a==$b)
{
$data = 'Yes they where the same';
};


echo $data;

?>

Why must I do like this?

<?php

$data = ''; // declare varibale
$a = 'a';
$b = 'b';

if($a==$b)
{
$data = 'Yes they where the same';
};


echo $data;

?>

Thanks for your answers!

Extending the question:

What is best practice:

$data = '';

or

$data;

or using

if (isset($data)){
echo $data;
}
Hakan
  • 3,835
  • 14
  • 45
  • 66

4 Answers4

4

What harm will it make if I echo an empty varibale?

There is no "empty" variable if you haven't defined it. So you're trying to output something that doesn't exist. Obviously it makes no sense and causes notices (try to run the script with E_ALL)

zerkms
  • 249,484
  • 69
  • 436
  • 539
3

The short answer: To avoid unnecessary errors and notices.

The long answer has been expounded upon here and here.

Community
  • 1
  • 1
deceze
  • 510,633
  • 85
  • 743
  • 889
1

Generally, it's better if you don't allow using nonexistent variables as if they were declared before, since this suppresses a whole class of errors. Imagine if you have a variable $foo, and later on you mistype $eoo. $eoo has no value (except the default), but your program will run with no complaints. This can make programs very difficult to debug. Requiring variables to be declared (for sure, not just conditionally) before their use lets the compiler catch a large number of bugs.

Rafe Kettler
  • 75,757
  • 21
  • 156
  • 151
  • @halfdan - I don't think that is really in the mainstream of PHP uses (at least yet). Or am I missing something? – Jared Farrish Nov 27 '11 at 23:16
  • @Jared A parser is for parsing text, a compiler is for compiling the parsed text. Even PHP has a compiler, even if it's basically used in the same step as the runtime. I don't think PHP's *compiler* catches missing variables though, the *runtime* does. – deceze Nov 27 '11 at 23:18
  • @deceze - Fair enough. Although, I would perhaps say *ensure variables are declared before use*, unless there is a way to require they are declared (like VBA's `Option Explicit`). – Jared Farrish Nov 27 '11 at 23:21
1

It will not cause any harm, but it will show you this notice:

PHP Notice: Undefined variable: data in on line

Jan Dragsbaek
  • 8,078
  • 2
  • 26
  • 46