SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Hybrid View

  1. #1
    if($awake){code();} PHP John's Avatar
    Join Date
    Jul 2002
    Location
    Along the Wasatch Fault line.
    Posts
    1,771
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    $array[key], $array['key'], $array["key"] ?

    I am wondering just what the differences between the following formats are:

    $array[key]

    $array['key']

    $array["key"]

    How does each affect performance?

    What are the advantages/disadvantages between each (if there are any)?
    John

  2. #2
    No. Phil.Roberts's Avatar
    Join Date
    May 2001
    Location
    Nottingham, UK
    Posts
    1,142
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    With:

    $array['key']
    $array["key"]

    They are functionally identical when mere referencing an array key name, but if you were to use a variable:

    $array['$key'] : Would pass a literal string '$key'
    $array["$key"] : Would pass the value of $key

    If you were to use:

    $array[key]

    Then PHP will first search for a defined constant named "key", if it doesnt find this, then it will regard it as a key name. If you were to set your error reporting to E_ALL you would see the results of using arrays in this fashion, and its to be avoided as it results in a loss of performance.

    Similar could be said for $array["$key"], as PHP will expect a string, but will also parse that string for variables. Another performance hit. Just use $array[ $key ].
    THE INSTRUCTIONS BELOW ARE OLD AND MAY BE INACCURATE.
    THIS INSTALL METHOD IS NOT RECOMMENDED, IT MAY RUN
    OVER YOUR DOG. <-- MediaWiki installation guide


Bookmarks

Posting Permissions

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