PHPBuilder - Getting Started With Arrays



RSS Twitter
Articles Php Functions

Getting Started With Arrays

by: PHP Builder Staff
|
March 2, 2012

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[10]. 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[0]="test text";

Associative

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:

 
$my_array=array("first_name"=>"Tim", "last_name"=>"Perdue");

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.

Multi-Dimensional Arrays

Yes, PHP supports multi-dimensional arrays. A lot of questions get asked about these on the mailing list and in the Support Forum.


$my_array[10][5];

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[0][0]="hello";
$my_array[0][1]="hello2";
$my_array[0][2]="hello3";
$my_array[0][3]="hello4";
$my_array[0][4]="hello5";    

So that populates the array in the first element of $my_array.


echo $my_array[0][4];

That will display hello5.

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:

Comment:



Comment:

(Maximum characters: 1200). You have characters left.