Is it necessary to declare PHP array before adding values with []?

PhpArrays

Php Problem Overview


$arr = array(); // is this line needed?
$arr[] = 5;

I know it works without the first line, but it's often included in practice.

What is the reason? Is it unsafe without it?

I know you can also do this:

 $arr = array(5);

but I'm talking about cases where you need to add items one by one.

Php Solutions


Solution 1 - Php

If you don't declare a new array, and the data that creates / updates the array fails for any reason, then any future code that tries to use the array will E_FATAL because the array doesn't exist.

For example, foreach() will throw an error if the array was not declared and no values were added to it. However, no errors will occur if the array is simply empty, as would be the case had you declared it.

Solution 2 - Php

Just wanted to point out that the PHP documentation on arrays actually talks about this in documentation.

From the PHP site, with accompanying code snippet:

$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value of any type

> "If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array."

But, as the other answers stated...you really should declare a value for your variables because all kind of bad things can happen if you don't.

Solution 3 - Php

Php is a loosely typed language. It's perfectly acceptable. That being said, real programmers always declare their vars.

Solution 4 - Php

Think of the coders who come after you! If you just see $arr[] = 5, you have no idea what $arr might be without reading all the preceding code in the scope. The explicit $arr = array() line makes it clear.

Solution 5 - Php

it's just good practice. Let's say you were appending to your array inside a loop (fairly common practice), but then accessing the array outside of said loop. Without an array declaration, your code would throw errors if you never made it into the loop.

Solution 6 - Php

I strongly recommend to declare the array before adding values. Besides everything mentioned above, if the array is inside a loop you might unintentionally push elements into your array. I just observed this creating a costly bug.

//Example code    
foreach ($mailboxes as $mailbox){
       //loop creating email list to get
       foreach ($emails as $email){
          $arr[] = $email;
       }
       //loop to get emails
       foreach ($arr as $email){
       //oops now we're getting other peoples emails
       //in other mailboxes because we didn't initialize the array
       }
}

Solution 7 - Php

By not declaring an array before using it can really cause problems. One experience I just found, I called this test script like this: indextest.php?file=1STLSPGTGUS This works as expected.

//indextest.php?file=1STLSPGTGUS
$path['templates']     = './mytemplates/';
$file['template']      = 'myindex.tpl.php';
$file['otherthing']      = 'otherthing';
$file['iamempty']    = '';
	  
print ("path['templates'] = " . $path['templates'] . "<br>");
print ("file['template'] = " . $file['template'] . "<br>");
print ("file['otherthing'] = " . $file['otherthing'] . "<br>");
print ("file['iamempty'] = " . $file['iamempty'] . "<br>");

print ("file['file'] = " . $file['file'] . "<br>");// should give: "Notice: Undefined index: file"
print ("file = " . $file);// should give: "Notice: Undefined index: file"

//the Output is:
/*
path['templates'] = ./mytemplates/
file['template'] = myindex.tpl.php
file['otherthing'] = otherthing
file['iamempty'] =

Notice: Undefined index: file in D:\Server\Apache24\htdocs\DeliverText\indextest.php on line 14
file['file'] =

Notice: Array to string conversion in D:\Server\Apache24\htdocs\DeliverText\indextest.php on line 15
file = Array
*/

Now I will just require a file, from another script I bought, at the top of mine and we can see how values are completly wrong for the array $file while array $path is OK: "checkgroup.php" is the guilty one.

//indextest.php?file=1STLSPGTGUS
require_once($_SERVER['DOCUMENT_ROOT']."/IniConfig.php");
$access = "PUBLIC";
require_once(CONFPATH . "include_secure/checkgroup.php");
$path['templates']     = './mytemplates/';
$file['template']      = 'myindex.tpl.php';
$file['otherthing']      = 'otherthing.php';
$file['iamempty']    = '';
		  
print ("path['templates'] = " . $path['templates'] . "<br>");
print ("file['template'] = " . $file['template'] . "<br>");
print ("file['otherthing'] = " . $file['otherthing'] . "<br>");
print ("file['iamempty'] = " . $file['iamempty'] . "<br>");

print ("file['file'] = " . $file['file'] . "<br>");
print ("file = " . $file);

//the Output is:
/*
path['templates'] = ./mytemplates/
file['template'] = o
file['otherthing'] = o
file['iamempty'] = o
file['file'] = o
file = oSTLSPGTGUS
*/

Initialising the array before, then no problem!

//indextest.php?file=1STLSPGTGUS
require_once($_SERVER['DOCUMENT_ROOT']."/IniConfig.php");
$access = "PUBLIC";
require_once(CONFPATH . "include_secure/checkgroup.php");

$path = array();
$file = array();

$path['templates']     = './mytemplates/';
$file['template']      = 'myindex.tpl.php';
$file['otherthing']      = 'otherthing.php';
$file['iamempty']    = '';

print ("path['templates'] = " . $path['templates'] . "<br>");
print ("file['template'] = " . $file['template'] . "<br>");
print ("file['otherthing'] = " . $file['otherthing'] . "<br>");
print ("file['iamempty'] = " . $file['iamempty'] . "<br>");

print ("file['file'] = " . $file['file'] . "<br>");
print ("file = " . $file);

//the Output is:
/*
path['templates'] = ./mytemplates/
file['template'] = myindex.tpl.php
file['otherthing'] = otherthing.php
file['iamempty'] =
file['file'] =
file = Array
*/

That's how I realised how important it is to initialise variables as we never know what problem we might end up with later, and just for wanting to save time we might end up wasting even more at the end. I hope this will be helpful for those like me who are not professional.

Solution 8 - Php

Old question but I share this as this is one use case where code is simpler if arrays are not declared.

Say you have a list of objects you need to index on one of their properties.

// $list is array of objects, all having $key property.
$index = [];
foreach ($list as $item)
    $index[$item->key][] = $item; // Dont care if $index[$item->key] already exists or not.

Solution 9 - Php

It depends on your error checking. If you have error reporting on strict it'll give you a notice but it should still technically work without it.

Solution 10 - Php

Its good in case when you need it as a global variable or want to reuse the same array again and again in different functions

Solution 11 - Php

This is your code

$var[]  = 2;
print_r($var)

Works fine! until someone declares the same variable name before your charming code

$var = 3; 

$var[]  = 2;
print_r($var)

>Warning: Cannot use a scalar value as an array

Oops!

This is one possible (sometimes unpredictable) case, so yes $var = array() is needed

$var = 3;
$var = array();
$var[]  = 2;
print_r($var)

Output

Array
(
    [0] => 2
)

Solution 12 - Php

For foreach loops if you're unsure of the data, then you can do this:

foreach($users ?? [] as $user) {
    // Do things with $user
}

If $users is not set (null coalesce does isset($users)) then you'll get the empty array [] and thus PHP won't loop the foreach as there's nothing to loop - no errors, warnings, or notices.

I disagree with some in the comments/answers, I don't think you should simply declare empty arrays or initialise variables just for the sake of it, as some kind of safety net. Such approaches is bad programming in my opinion. Do it explicitly when it's necessary.

And to be honest, if you have to initialise an empty array, consider if the code could be better structured, how you check for data later on or whatever.

The following code is pointless, it doesn't show "intent" it can just confuse people as to why it's initialised (at best it's just something pointless to read and process):

$user = [];
$user['name'] = ['bob'];

The 2nd line also declares the new array and will never fail.

Solution 13 - Php

Agree with @djdy, just one alternative I'd love to post:

<?php

// Passed array is empty, so we'll never have $items variable available.
foreach (array() AS $item)
    $items[] = $item;

isset($items) OR $items = array(); // Declare $items variable if it doesn't exist

?>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionryanveView Question on Stackoverflow
Solution 1 - PhpdjdyView Answer on Stackoverflow
Solution 2 - PhpCharles SprayberryView Answer on Stackoverflow
Solution 3 - PhpAlienWebguyView Answer on Stackoverflow
Solution 4 - PhpRob AgarView Answer on Stackoverflow
Solution 5 - PhpJulienView Answer on Stackoverflow
Solution 6 - Phpykay says Reinstate MonicaView Answer on Stackoverflow
Solution 7 - PhpDan BonView Answer on Stackoverflow
Solution 8 - PhpjaissonView Answer on Stackoverflow
Solution 9 - PhpbrenjtView Answer on Stackoverflow
Solution 10 - PhpVinitView Answer on Stackoverflow
Solution 11 - PhpRainView Answer on Stackoverflow
Solution 12 - PhpJamesView Answer on Stackoverflow
Solution 13 - PhpOtarView Answer on Stackoverflow