Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Jun 2002
    Location
    North of Boston
    Posts
    29
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question multi-dimensional arrays

    I am studying php and am on a chapter dealing with arrays.
    I am trying to write a script which prints to the screen 2 items in a multi-dimensional array. Now I read there are 2 ways to do a MD array
    1. $master_array =array('array1','array2');
    $array1=array('item1','item2');
    $array2=array('item1','item2');

    2.$master_array=array('array1'=>('item1','item2'),'array2'=>array('item1','item2'));

    When I use the first method and put the code
    PHP Code:
    print($master_array[0][0]); 
    its prints array1 item1

    but when I use the same print code for the 2nd method it does nothing unless
    I change the first item to the actual name of the array. i.e.
    PHP Code:
    print($master_array['array1'][0]); 
    am I doing something wrong or is that how it works?
    bedardinc.com
    A+,Network+, MCP W2K
    Sites I have worked on
    patriotsweekly.com
    smileysbookstore.com

  • #2
    Regular Coder
    Join Date
    Jun 2005
    Posts
    804
    Thanks
    0
    Thanked 0 Times in 0 Posts
    For each element of an array, there are two parts -- an index and a value. The value, of course, is the data you're putting into the array. The index is an identifier for that piece of data. Indexes can be numbers or strings. When you create an array or add an element to an existing array, you're setting both of these elements. But in method two:

    $master_array =array('array1','array2');

    you're only setting values. This is ok, though, because the array() construct recognizes this and creates numeric indexes (0 and 1, as you already know) for you.

    In method two, though,

    $master_array=array('array1'=>array('item1','item2'));

    you're specifying that the string 'array1' is the index. In this case, array() will not create a numeric index for you, which is why trying to refer to it numerically won't work.

  • #3
    New Coder
    Join Date
    Jun 2002
    Location
    North of Boston
    Posts
    29
    Thanks
    0
    Thanked 0 Times in 0 Posts


    Thanks for clearing that up. The tutorial I am following does not differentiate between the 2.
    bedardinc.com
    A+,Network+, MCP W2K
    Sites I have worked on
    patriotsweekly.com
    smileysbookstore.com


  •  

    Posting Permissions

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