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










73














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










share|improve this question



















  • 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.).
    – Brad Christie
    Nov 23 '11 at 16:57







  • 6




    @Brad Christie: Except that doesn't trigger such a notice.
    – BoltClock
    Nov 23 '11 at 16:58







  • 3




    @BoltClock: Depends which version you're working on.
    – Brad Christie
    Nov 23 '11 at 16:59















73














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










share|improve this question



















  • 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.).
    – Brad Christie
    Nov 23 '11 at 16:57







  • 6




    @Brad Christie: Except that doesn't trigger such a notice.
    – BoltClock
    Nov 23 '11 at 16:58







  • 3




    @BoltClock: Depends which version you're working on.
    – Brad Christie
    Nov 23 '11 at 16:59













73












73








73


5





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










share|improve this question















$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 arrays






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 14 '15 at 12:44









Dilip Raj Baral

1,71252247




1,71252247










asked Nov 23 '11 at 16:54









ryanve

27.3k2270109




27.3k2270109







  • 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.).
    – Brad Christie
    Nov 23 '11 at 16:57







  • 6




    @Brad Christie: Except that doesn't trigger such a notice.
    – BoltClock
    Nov 23 '11 at 16:58







  • 3




    @BoltClock: Depends which version you're working on.
    – Brad Christie
    Nov 23 '11 at 16:59












  • 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.).
    – Brad Christie
    Nov 23 '11 at 16:57







  • 6




    @Brad Christie: Except that doesn't trigger such a notice.
    – BoltClock
    Nov 23 '11 at 16:58







  • 3




    @BoltClock: Depends which version you're working on.
    – Brad Christie
    Nov 23 '11 at 16:59







2




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.).
– Brad Christie
Nov 23 '11 at 16:57





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.).
– Brad Christie
Nov 23 '11 at 16:57





6




6




@Brad Christie: Except that doesn't trigger such a notice.
– BoltClock
Nov 23 '11 at 16:58





@Brad Christie: Except that doesn't trigger such a notice.
– BoltClock
Nov 23 '11 at 16:58





3




3




@BoltClock: Depends which version you're working on.
– Brad Christie
Nov 23 '11 at 16:59




@BoltClock: Depends which version you're working on.
– Brad Christie
Nov 23 '11 at 16:59












11 Answers
11






active

oldest

votes


















85














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.






share|improve this answer






















  • Upvoted because the foreach example and the fact that an error being triggered is apparently dependent on the version of PHP you're running.
    – Charles Sprayberry
    Nov 23 '11 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 '11 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 '11 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 '12 at 17:45


















23














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.






share|improve this answer




























    13














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






    share|improve this answer
















    • 28




      real programmers
      – Gordon
      Nov 23 '11 at 17:02






    • 1




      @Gordon exactly what I was thinking ;)
      – AlienWebguy
      Nov 23 '11 at 20:55


















    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.






    share|improve this answer
















    • 1




      In PHP 5.4.x - 5.6.x: $arr = works, too.
      – Anthony Rutledge
      Sep 25 '15 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.






    share|improve this answer




























      3














      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







      share|improve this answer






















      • Don't do what??
        – ryanve
        Dec 6 '17 at 21:54






      • 1




        @ryanve i've edited the answer
        – ykay
        Dec 7 '17 at 8:10


















      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:ServerApache24htdocsDeliverTextindextest.php on line 14
      file['file'] =

      Notice: Array to string conversion in D:ServerApache24htdocsDeliverTextindextest.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.






      share|improve this answer




























        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.






        share|improve this answer




























          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






          share|improve this answer




























            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
            )





            share|improve this answer




























              -1














              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

              ?>





              share|improve this answer




















              • What's the point of all of this? Seems much ado about literally nothing.
                – BoltClock
                Nov 23 '11 at 17:10










              • Instead of pre-declaring $items variable you'll check existence a loop, that's all.
                – Otar
                Nov 23 '11 at 17:14










              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f8246047%2fis-it-necessary-to-declare-php-array-before-adding-values-with%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              11 Answers
              11






              active

              oldest

              votes








              11 Answers
              11






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              85














              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.






              share|improve this answer






















              • Upvoted because the foreach example and the fact that an error being triggered is apparently dependent on the version of PHP you're running.
                – Charles Sprayberry
                Nov 23 '11 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 '11 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 '11 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 '12 at 17:45















              85














              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.






              share|improve this answer






















              • Upvoted because the foreach example and the fact that an error being triggered is apparently dependent on the version of PHP you're running.
                – Charles Sprayberry
                Nov 23 '11 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 '11 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 '11 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 '12 at 17:45













              85












              85








              85






              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.






              share|improve this answer














              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.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Jul 22 '13 at 10:13









              Jimbo

              18.8k1167105




              18.8k1167105










              answered Nov 23 '11 at 16:58









              djdy

              5,60343260




              5,60343260











              • Upvoted because the foreach example and the fact that an error being triggered is apparently dependent on the version of PHP you're running.
                – Charles Sprayberry
                Nov 23 '11 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 '11 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 '11 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 '12 at 17:45
















              • Upvoted because the foreach example and the fact that an error being triggered is apparently dependent on the version of PHP you're running.
                – Charles Sprayberry
                Nov 23 '11 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 '11 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 '11 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 '12 at 17:45















              Upvoted because the foreach example and the fact that an error being triggered is apparently dependent on the version of PHP you're running.
              – Charles Sprayberry
              Nov 23 '11 at 17:02




              Upvoted because the foreach example and the fact that an error being triggered is apparently dependent on the version of PHP you're running.
              – Charles Sprayberry
              Nov 23 '11 at 17:02




              1




              1




              I dont understand that answer. Not declared and not added something means I did not write in into the sourcecode.
              – Gordon
              Nov 23 '11 at 17:13





              I dont understand that answer. Not declared and not added something means I did not write in into the sourcecode.
              – Gordon
              Nov 23 '11 at 17:13





              2




              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 '11 at 17:42





              @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 '11 at 17:42





              1




              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 '12 at 17:45




              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 '12 at 17:45













              23














              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.






              share|improve this answer

























                23














                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.






                share|improve this answer























                  23












                  23








                  23






                  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.






                  share|improve this answer












                  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.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 23 '11 at 17:06









                  Charles Sprayberry

                  6,90823047




                  6,90823047





















                      13














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






                      share|improve this answer
















                      • 28




                        real programmers
                        – Gordon
                        Nov 23 '11 at 17:02






                      • 1




                        @Gordon exactly what I was thinking ;)
                        – AlienWebguy
                        Nov 23 '11 at 20:55















                      13














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






                      share|improve this answer
















                      • 28




                        real programmers
                        – Gordon
                        Nov 23 '11 at 17:02






                      • 1




                        @Gordon exactly what I was thinking ;)
                        – AlienWebguy
                        Nov 23 '11 at 20:55













                      13












                      13








                      13






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






                      share|improve this answer












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







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Nov 23 '11 at 17:00









                      AlienWebguy

                      66.2k1393127




                      66.2k1393127







                      • 28




                        real programmers
                        – Gordon
                        Nov 23 '11 at 17:02






                      • 1




                        @Gordon exactly what I was thinking ;)
                        – AlienWebguy
                        Nov 23 '11 at 20:55












                      • 28




                        real programmers
                        – Gordon
                        Nov 23 '11 at 17:02






                      • 1




                        @Gordon exactly what I was thinking ;)
                        – AlienWebguy
                        Nov 23 '11 at 20:55







                      28




                      28




                      real programmers
                      – Gordon
                      Nov 23 '11 at 17:02




                      real programmers
                      – Gordon
                      Nov 23 '11 at 17:02




                      1




                      1




                      @Gordon exactly what I was thinking ;)
                      – AlienWebguy
                      Nov 23 '11 at 20:55




                      @Gordon exactly what I was thinking ;)
                      – AlienWebguy
                      Nov 23 '11 at 20:55











                      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.






                      share|improve this answer
















                      • 1




                        In PHP 5.4.x - 5.6.x: $arr = works, too.
                        – Anthony Rutledge
                        Sep 25 '15 at 15:25















                      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.






                      share|improve this answer
















                      • 1




                        In PHP 5.4.x - 5.6.x: $arr = works, too.
                        – Anthony Rutledge
                        Sep 25 '15 at 15:25













                      6












                      6








                      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.






                      share|improve this answer












                      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.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Nov 23 '11 at 17:10









                      Rob Agar

                      9,48733655




                      9,48733655







                      • 1




                        In PHP 5.4.x - 5.6.x: $arr = works, too.
                        – Anthony Rutledge
                        Sep 25 '15 at 15:25












                      • 1




                        In PHP 5.4.x - 5.6.x: $arr = works, too.
                        – Anthony Rutledge
                        Sep 25 '15 at 15:25







                      1




                      1




                      In PHP 5.4.x - 5.6.x: $arr = works, too.
                      – Anthony Rutledge
                      Sep 25 '15 at 15:25




                      In PHP 5.4.x - 5.6.x: $arr = works, too.
                      – Anthony Rutledge
                      Sep 25 '15 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.






                      share|improve this answer

























                        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.






                        share|improve this answer























                          4












                          4








                          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.






                          share|improve this answer












                          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.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 23 '11 at 16:57









                          Julien

                          60511139




                          60511139





















                              3














                              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







                              share|improve this answer






















                              • Don't do what??
                                – ryanve
                                Dec 6 '17 at 21:54






                              • 1




                                @ryanve i've edited the answer
                                – ykay
                                Dec 7 '17 at 8:10















                              3














                              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







                              share|improve this answer






















                              • Don't do what??
                                – ryanve
                                Dec 6 '17 at 21:54






                              • 1




                                @ryanve i've edited the answer
                                – ykay
                                Dec 7 '17 at 8:10













                              3












                              3








                              3






                              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







                              share|improve this answer














                              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








                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Dec 7 '17 at 8:09

























                              answered Dec 6 '17 at 12:21









                              ykay

                              1,6171829




                              1,6171829











                              • Don't do what??
                                – ryanve
                                Dec 6 '17 at 21:54






                              • 1




                                @ryanve i've edited the answer
                                – ykay
                                Dec 7 '17 at 8:10
















                              • Don't do what??
                                – ryanve
                                Dec 6 '17 at 21:54






                              • 1




                                @ryanve i've edited the answer
                                – ykay
                                Dec 7 '17 at 8:10















                              Don't do what??
                              – ryanve
                              Dec 6 '17 at 21:54




                              Don't do what??
                              – ryanve
                              Dec 6 '17 at 21:54




                              1




                              1




                              @ryanve i've edited the answer
                              – ykay
                              Dec 7 '17 at 8:10




                              @ryanve i've edited the answer
                              – ykay
                              Dec 7 '17 at 8:10











                              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:ServerApache24htdocsDeliverTextindextest.php on line 14
                              file['file'] =

                              Notice: Array to string conversion in D:ServerApache24htdocsDeliverTextindextest.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.






                              share|improve this answer

























                                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:ServerApache24htdocsDeliverTextindextest.php on line 14
                                file['file'] =

                                Notice: Array to string conversion in D:ServerApache24htdocsDeliverTextindextest.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.






                                share|improve this answer























                                  1












                                  1








                                  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:ServerApache24htdocsDeliverTextindextest.php on line 14
                                  file['file'] =

                                  Notice: Array to string conversion in D:ServerApache24htdocsDeliverTextindextest.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.






                                  share|improve this answer












                                  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:ServerApache24htdocsDeliverTextindextest.php on line 14
                                  file['file'] =

                                  Notice: Array to string conversion in D:ServerApache24htdocsDeliverTextindextest.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.







                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Nov 12 '18 at 0:39









                                  Dan Bon

                                  134




                                  134





















                                      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.






                                      share|improve this answer

























                                        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.






                                        share|improve this answer























                                          0












                                          0








                                          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.






                                          share|improve this answer












                                          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.







                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Nov 23 '11 at 16:57









                                          brenjt

                                          11.1k1167105




                                          11.1k1167105





















                                              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






                                              share|improve this answer

























                                                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






                                                share|improve this answer























                                                  0












                                                  0








                                                  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






                                                  share|improve this answer












                                                  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







                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Nov 23 '11 at 16:59









                                                  Vinit

                                                  1,5151235




                                                  1,5151235





















                                                      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
                                                      )





                                                      share|improve this answer

























                                                        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
                                                        )





                                                        share|improve this answer























                                                          0












                                                          0








                                                          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
                                                          )





                                                          share|improve this answer












                                                          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
                                                          )






                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Dec 10 '18 at 16:45









                                                          FatalError

                                                          403311




                                                          403311





















                                                              -1














                                                              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

                                                              ?>





                                                              share|improve this answer




















                                                              • What's the point of all of this? Seems much ado about literally nothing.
                                                                – BoltClock
                                                                Nov 23 '11 at 17:10










                                                              • Instead of pre-declaring $items variable you'll check existence a loop, that's all.
                                                                – Otar
                                                                Nov 23 '11 at 17:14















                                                              -1














                                                              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

                                                              ?>





                                                              share|improve this answer




















                                                              • What's the point of all of this? Seems much ado about literally nothing.
                                                                – BoltClock
                                                                Nov 23 '11 at 17:10










                                                              • Instead of pre-declaring $items variable you'll check existence a loop, that's all.
                                                                – Otar
                                                                Nov 23 '11 at 17:14













                                                              -1












                                                              -1








                                                              -1






                                                              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

                                                              ?>





                                                              share|improve this answer












                                                              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

                                                              ?>






                                                              share|improve this answer












                                                              share|improve this answer



                                                              share|improve this answer










                                                              answered Nov 23 '11 at 17:06









                                                              Otar

                                                              2,09511723




                                                              2,09511723











                                                              • What's the point of all of this? Seems much ado about literally nothing.
                                                                – BoltClock
                                                                Nov 23 '11 at 17:10










                                                              • Instead of pre-declaring $items variable you'll check existence a loop, that's all.
                                                                – Otar
                                                                Nov 23 '11 at 17:14
















                                                              • What's the point of all of this? Seems much ado about literally nothing.
                                                                – BoltClock
                                                                Nov 23 '11 at 17:10










                                                              • Instead of pre-declaring $items variable you'll check existence a loop, that's all.
                                                                – Otar
                                                                Nov 23 '11 at 17:14















                                                              What's the point of all of this? Seems much ado about literally nothing.
                                                              – BoltClock
                                                              Nov 23 '11 at 17:10




                                                              What's the point of all of this? Seems much ado about literally nothing.
                                                              – BoltClock
                                                              Nov 23 '11 at 17:10












                                                              Instead of pre-declaring $items variable you'll check existence a loop, that's all.
                                                              – Otar
                                                              Nov 23 '11 at 17:14




                                                              Instead of pre-declaring $items variable you'll check existence a loop, that's all.
                                                              – Otar
                                                              Nov 23 '11 at 17:14

















                                                              draft saved

                                                              draft discarded
















































                                                              Thanks for contributing an answer to Stack Overflow!


                                                              • Please be sure to answer the question. Provide details and share your research!

                                                              But avoid


                                                              • Asking for help, clarification, or responding to other answers.

                                                              • Making statements based on opinion; back them up with references or personal experience.

                                                              To learn more, see our tips on writing great answers.





                                                              Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                              Please pay close attention to the following guidance:


                                                              • Please be sure to answer the question. Provide details and share your research!

                                                              But avoid


                                                              • Asking for help, clarification, or responding to other answers.

                                                              • Making statements based on opinion; back them up with references or personal experience.

                                                              To learn more, see our tips on writing great answers.




                                                              draft saved


                                                              draft discarded














                                                              StackExchange.ready(
                                                              function ()
                                                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f8246047%2fis-it-necessary-to-declare-php-array-before-adding-values-with%23new-answer', 'question_page');

                                                              );

                                                              Post as a guest















                                                              Required, but never shown





















































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown

































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown







                                                              Popular posts from this blog

                                                              Use pre created SQLite database for Android project in kotlin

                                                              Darth Vader #20

                                                              Ondo