Jump to content

Should arrays be initialized?


NotionCommotion

Recommended Posts

As long as I am certain that $arr hasn't been previously assigned and that I am not concerned attempting to use it and getting an unset warning, is there any reason to initiate arrays before using them?

<?php


//$arr=[];
foreach([[2,3,1],[0,4,2],[1,4,3],[2,4,4]] as $e) {
    //if(!isset($arr[$e[0]])) $arr[$e[0]]=[];
    $arr[$e[0]][$e[1]]=$e[2];
}
var_dump($arr);

 

Link to comment
Share on other sites

Meaning if you read the information on that page it will answer your question.

 

I interpret that obscure post  to be that it is acceptable, however, I don't feel it is an authoritative source and it might be outdated being over 13 years old.  And while attempting to do so does not create an error, that does not mean one should do so.  According to http://php.net/manual/en/language.types.array.php, it is discouraged as it might be previously set as a string before doing so.

Link to comment
Share on other sites

I'd say it comes down more to your preference. I like to initialize my variables (any, not just array) if their value is generated through a loop, branching statements, etc. I find it makes the code more readable.

 

If you're following good practices such as meaningful variable names and separating code into various functions/classes then you shouldn't have problems with your array variable being previously defined as some other type.

Link to comment
Share on other sites

NotionCommotion, it depends... If you don't initialize arrays, in most of situations it will be fine even if you set error_reporting to E_ALL.

 

However, you might encounter situations when it will produce undefined variable error; therefore, I would recommend initializing arrays. This way, you are sure that code doesn't raise any errors on different server environments.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.