PHP: The correct way to declare a variable before using in a loop

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

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

If $ str = "" is excluded, I get an undefined variable notification, but I thought php would automatically declare the variable the first time it sees an undeclared?

How to do it right?

+7
performance loops php
source share
4 answers

You get an undefined variable because you combine the value of yourself with another value.

Equivalent

$str = $str . "something";

Thus, he cannot say what the initial meaning is. This is equivalent to this:

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

What is the result of concatenating [undefined value] and "something" ? The interpreter cannot say ...

So, you must first put the "" in the variable to initialize the value of the variable, just like you.

NTN

+14
source share

If you really need to make it cleaner, you can do:

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

But you have what I usually do. vlceBerg explains this well.

+8
source share

It’s safer not to use the auto-announce feature β€” why does it issue a notification. Notification is the lowest warning level and will not be displayed by default. Most older PHP applications will generate a lot of notifications if you enable them.

+4
source share

PHP variables that were automatically declared are registered as undefined, so you get a notification.

It's usually best to declare PHP variables before using them, although many of the lazy ones among us, including myself, don't always do this.

+2
source share

All Articles