www.webdeveloper.com
Results 1 to 5 of 5

Thread: Any difference between $arr['key'] and $arr[key]

  1. #1
    Join Date
    Nov 2005
    Location
    India
    Posts
    336

    Any difference between $arr['key'] and $arr[key]

    Hello,

    Could someone tell me if there's a difference between $arr['key'] and $arr[key] (without quotation marks)? Thanks.

  2. #2
    Join Date
    Mar 2010
    Posts
    2,803
    $arr['key'] is an element of an associative array as opposed to an indexed array.

    I have always had the associative array key enclosed in single quotes because that is the way I was taught and so have always assumed an error would be generated if the quotes were omitted - but I could be wrong.

    Why, what happens if you echo $arr[key]? Did you not get an error?

    Unless you are thinking of $arr[$someVar] which is valid if $someVar is a string or integer
    Last edited by tirna; 07-28-2010 at 07:50 AM.

  3. #3
    Join Date
    Jan 2009
    Posts
    3,346
    If the quotes are omitted the php engine checks for a constant. If the constant doesn't exist then it throws a "notice" error a "corrects" the quotes for you. It is better practice to use the quotes (unless you are indeed referencing a constant).

  4. #4
    Join Date
    Nov 2002
    Location
    Baltimore, Maryland
    Posts
    12,270
    The problem is one of forward compatibility. $arr[key] might work today but one day in the future key might be a constant.
    “The power of the Web is in its universality. Access by everyone regardless of disability is an essential aspect.”
    —Tim Berners-Lee, W3C Director and inventor of the World Wide Web

  5. #5
    Join Date
    Aug 2007
    Posts
    3,767
    php.net now say it's wrong, except when parsed in a string.
    Last edited by Declan1991; 07-28-2010 at 10:18 AM.
    Great wit and madness are near allied, and fine a line their bounds divide.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles