Jump to content

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
https://forums.phpfreaks.com/topic/305172-should-arrays-be-initialized/
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.

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.

  • Like 1

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.