Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.php > #12885

Re: Declaring an array necessary?

From Daniel Pitts <newsgroup.nospam@virtualinfinity.net>
Newsgroups comp.lang.php
Subject Re: Declaring an array necessary?
References <le840m$8kk$1@news.albasani.net>
Message-ID <73QNu.7865$Z04.5437@fx27.iad> (permalink)
Date 2014-02-21 14:03 -0800

Show all headers | View raw


On 2/21/14 9:56 AM, The Natural Philosopher wrote:
> I was just wondering. Php assumes a varibale exists as soon as it is
> assigned a value, but a function exists to create an array..
> Sop can one just say
>
> $arr['hello']='sexy';
>
> or should there be
>
> $arr=array();
>
> first?
>
>

Necessary, no, but it is still a best practice.  It helps with 
maintenance later, as well as it clearly states your intent.

Imagine this scenario: You start with

function createMyArray($someData) {

   $arr['theData'] = $someData->getX();
   $arr['theOtherData'] = $someData->getY();

   return $arr;
}


A few weeks later, you get a bug report that you need to only sometimes 
add getX().

function createMyArray($someData) {

   if ($someData->isFoo()) {
     $arr['theData'] = $someData->getX();
   }
   $arr['theOtherData'] = $someData->getY();

   return $arr;
}

Then, you (or someone else) finds out getY() is optional...


function createMyArray($someData) {

   if ($someData->isFoo()) {
     $arr['theData'] = $someData->getX();
   }
   if ($someData->isBar()) {
     $arr['theOtherData'] = $someData->getY();
   }

   return $arr;
}


Oh no! You've just introduced a bug where if isFoo and isBar returns 
true, then $arr is not set!


Now, if the original author had just added "$arr = []"; things would 
have never progressed to this state.  It's called defensive programming. 
Doing certain things you know aren't strictly necessary now, but might 
be necessary, or clear up possible confusion.

Back to comp.lang.php | Previous | Next — Previous in thread | Find similar | Unroll thread


Thread

Declaring an array necessary? The Natural Philosopher <tnp@invalid.invalid> - 2014-02-21 17:56 +0000
  Re: Declaring an array necessary? Christian Stadler <stadli@gmx.de> - 2014-02-21 21:04 +0100
    Re: Declaring an array necessary? Jerry Stuckle <jstucklex@attglobal.net> - 2014-02-21 15:48 -0500
    Re: Declaring an array necessary? The Natural Philosopher <tnp@invalid.invalid> - 2014-02-21 21:32 +0000
      Re: Declaring an array necessary? Gregor Kofler <usenet@gregorkofler.com> - 2014-02-21 22:55 +0100
        Re: Declaring an array necessary? Tim Streater <timstreater@greenbee.net> - 2014-02-21 22:06 +0000
  Re: Declaring an array necessary? "M. Strobel" <sorry_no_mail_here@nowhere.dee> - 2014-02-21 22:58 +0100
  Re: Declaring an array necessary? Daniel Pitts <newsgroup.nospam@virtualinfinity.net> - 2014-02-21 14:03 -0800

csiph-web