7

I have a variable that is built in loop. Something like:

$str = "";
for($i = 0; $i < 10; $i++) $str .= "something";

If $str = "" is ommitted, I get undefined variable notice, but I thought php auto-declare a variable the first time it sees undeclared one?

How do I do this right?

4 Answers 4

15

You get the undefined variable because you're concatenating the value of itself with another value.

The equivalent of

$str = $str . "something";

So, it can't say what's the initial value is. It's the equivalent of this:

$str = [undefined value] . "something";

What's the result of a concatenation of [undefined value] and "something"? The interpreter can't say...

So, you have to put "" in the variable first to initiate the variable's value, as you did.

HTH

1
  • I was supposing variable scope also applies to loops as well but yeah you are right same thing happened to me and I now understand the reason. +1
    – Tarik
    Jul 8, 2011 at 8:12
8

If you really need to make it a it cleaner you could do:

for($i = 0, $str = ''; $i < 10; $i++) $str .= "something";

But what you have is what I normally do. vlceBerg explains it well.

3
  • 1
    Just a thought... can you do this: for($i = 0, $str = ''; $i < 10; $i++, $str .= "something"); ? I don't have a PHP box right now to test....
    – vIceBerg
    Oct 28, 2008 at 16:35
  • 1
    Apparently yes: zsh % echo '<? for($i = 0, $str = ""; $i < 10; $i++, $str .= "something"); echo $str; ?>' | php somethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomething Oct 28, 2008 at 16:48
  • Yep vlceBerg - you don't even need the loop content. I find it easier to understand using the content but seeing as it's one line you don't need to.
    – Ross
    Oct 31, 2008 at 11:21
4

It's safer to not use the auto-declare feature - that's why it issues a notice. A notice is the lowest level of warning, and won't be displayed by default. Most older PHP apps will issue lots of notices if you were to turn them on.

2

PHP variables that are auto-declared are registered as being undefined which is why you're receiving the notice.

It is generally better to declare PHP variables prior to using them though many of the lazy among us, myself included don't always do that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.