OK, I needed to use arrays to create my graphing functions that I detailed in my article “HTML_Graphs” here on this site.
Unfortunately, arrays are way different in PHP than in my native programming language, Java. In Java, you define an array as a fixed length item, like my_array. It cannot be grown beyond 10 elements.
PHP is cooler than that: it’s smart enough to keep extending your arrays for as long as you like. You really don’t even have to declare the array before you start adding stuff to it. For good form, I usually like to declare my array first, as something like this: my_array;
Another interesting feature is that you don’t really have to specify the index where you want your element added. If you leave the array index blank, PHP will just glom your value onto the end of the array: my_array=”test text”;. “test text” will simply be added to a new element at the end of the array. I personally don’t like to do that, as it seems sloppy and unstructured. I always give it an index, so I know where the item was put in the array: my_array=”test text”;
You can also create associative arrays, where you reference a given element using a name, like: echo $my_array[“first_name”];.
To create an array like that, you would use the array() function:
I suppose the benefit to using associations like that, is so you can pass a number of values into a function, rather than passing in each value separately. I don’t use associative arrays much; it’s easier to simply set up values like $first_name=”Tim” and $last_name=”Perdue”;. Less code is involved.
Yes, PHP supports multi-dimensional arrays. A lot of questions get asked about these on the mailing list and in the Support Forum.
That creates an array with 10 elements; each of those elements is an array with 5 elements. I suppose again, you could do it free-form and not declare any dimensions.
To set values in that array, do it as you would do it in any programming language:
$my_array="hello"; $my_array="hello2"; $my_array="hello3"; $my_array="hello4"; $my_array="hello5";
So that populates the array in the first element of $my_array.
That will display hello5.