93
$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.). Commented Nov 23, 2011 at 16:57
  • 7
    @Brad Christie: Except that doesn't trigger such a notice. Commented Nov 23, 2011 at 16:58
  • 3
    @BoltClock: Depends which version you're working on. Commented Nov 23, 2011 at 16:59

13 Answers 13

96

It's recommended to always initialize arrays before use. Right from the PHP manual:

If $arr doesn't exist yet or is set to null or false, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place ... It is always better to initialize a variable by a direct assignment.

Also, if adding new values is conditional, and no values gets actually added, it will lead to infamous Undefined variable Warning level error.

For example, foreach() will throw such 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.

Sign up to request clarification or add additional context in comments.

4 Comments

Upvoted because the foreach example and the fact that an error being triggered is apparently dependent on the version of PHP you're running.
I dont understand that answer. Not declared and not added something means I did not write in into the sourcecode.
@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.
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.
26

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.

Comments

13

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

2 Comments

@Gordon exactly what I was thinking ;)
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
6

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 Comment

In PHP 5.4.x - 5.6.x: $arr = [] works, too.
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.

Comments

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 Comment

Don't do what??
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.

Comments

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.

Comments

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.

Comments

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

Comments

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
)

Comments

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.

Comments

-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 Comments

What's the point of all of this? Seems much ado about literally nothing.
Instead of pre-declaring $items variable you'll check existence a loop, that's all.
array() is empty array, the foreach will never do anything?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.