90
$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.

3
  • 2
    Unless you like notices about undeclared variables, I would recommend to initialize. Plus, it just makes for legible code (it's clear that $foo = array() and that it wasn't a string turned in to an array, etc.). Nov 23, 2011 at 16:57
  • 6
    @Brad Christie: Except that doesn't trigger such a notice.
    – BoltClock
    Nov 23, 2011 at 16:58
  • 3
    @BoltClock: Depends which version you're working on. Nov 23, 2011 at 16:59

13 Answers 13

94

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.

4
  • Upvoted because the foreach example and the fact that an error being triggered is apparently dependent on the version of PHP you're running. Nov 23, 2011 at 17:02
  • 1
    I dont understand that answer. Not declared and not added something means I did not write in into the sourcecode.
    – Gordon
    Nov 23, 2011 at 17:13
  • 2
    @Gordon, example of something that will not work right if $something is not equal to 1: if($something == 1) { $rows[] = "a"; $rows[] = "b"; } foreach($rows as $row) { } The error could've been avoided had $rows been declared as $rows = array(); before the if statement happened.
    – djdy
    Nov 23, 2011 at 17:42
  • 1
    I agree (I voted up) but life is too short to declare everything, all the time, even though we know it's the "right" thing to do. Alternatively, I'm guessing you can use is_array() if you're concerned about undeclared arrays. Like most things, depends on the particulars.
    – PJ Brunet
    Dec 12, 2012 at 17:45
27

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.

14

Php is a loosely typed language. It's perfectly acceptable.

2
  • 2
    @Gordon exactly what I was thinking ;) Nov 23, 2011 at 20:55
  • Sorry, but "real" programmes code in such a way that they 99% of the time don't need to declare vars. And usually use an object that handles potential empty data such as null
    – James
    Dec 3, 2020 at 0:36
7

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.

1
  • 2
    In PHP 5.4.x - 5.6.x: $arr = [] works, too. Sep 25, 2015 at 15:25
4

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.

4

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
       }
}
1
  • Don't do what??
    – ryanve
    Dec 6, 2017 at 21:54
1

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.

1

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.
0

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.

0

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

0

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
)
0

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.

-3

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

?>
3
  • 1
    What's the point of all of this? Seems much ado about literally nothing.
    – BoltClock
    Nov 23, 2011 at 17:10
  • Instead of pre-declaring $items variable you'll check existence a loop, that's all.
    – Otar
    Nov 23, 2011 at 17:14
  • array() is empty array, the foreach will never do anything?
    – James
    Dec 3, 2020 at 0:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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