Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Simple piece of code, in which we want to store the element of array (which in turn is another array) in another variable:

Global $arr[1][2] = [ [1, 2] ]
Global $sub = $arr[0]

And we get

Array variable has incorrect number of subscripts or subscript dimension range exceeded.:
Global $sub = $arr[0]
Global $sub = ^ ERROR

If we write

Global $arr[1][2] = [ [1, 2] ]
Global $sub[2] = $arr[0]

We get

Missing subscript dimensions in "Dim" statement.:
Global $sub[2] = $arr[0]
Global $sub[2] = ^ ERROR

So simple task, but I didn't find the way how I can do it. Have no idea. Please, help.

share|improve this question

1 Answer 1

up vote 3 down vote accepted

Your first assumption, that you declare an array inside another array, is incorrect. You are actually creating a multi-dimensional array, which with 2 dimensions can be considered a grid (but the term is not used). The difference between the two is as follows:

  • Multi-dimensional array:

    Local $arr[1][2] = [ [1, 2] ]
    Local $sub = $arr[0][0] ; value = 1
    
  • Array inside array:

    Local $firstArray[2] = [1, 2]
    Local $arr[1] = [ $firstArray ]
    ;Local $sub = $arr[0][0] ; This does not work
    
    Local $sub = $arr[0]
    $sub = $sub[0] ; value = 1
    

Generally you will prefer a multi-dimensional array. An array inside another array is a bit dramatic, but it can sometimes be considered good practice to use an array inside another array.

As a final tip, do not use the Global keyword to define variables but use the Local keyword instead. If you declare variables with the local keyword you avoid poluting the global namespace inappropriately.

share|improve this answer
    
Clear, short and comprehensive answer. That was a challenge to my mind to realize that multidimentional arrays are not arrays of arrays as it is in all programming languages that I used. Thanks! –  disfated Feb 15 '11 at 6:42

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.