Wednesday, April 30, 2008

Arrays and Array Processing in PHP

Arrays are a set of variables of the same data type. If you’ve ever programmed before you should be knowing about it. but PHP takes arrays to the next level by providing so many useful in-built features to operate on them, let’s see some of them.

Types of Arrays

You should be familiar with the following type of array:


It is an example of numerically indexed array since numerical values are used as indices to reference different elements of the array.

One other type of array that PHP supports is those having string indices which sometimes may make indexing more meaningful.


This type of array is also called Associative Arrays.

As is obvious, the array above should most probably be having temperatures of different months. Had it been numerically indexed, it wouldn’t have made that much sense. So you can use these types of arrays to make indexing and referencing of elements more meaningful.

Initializing Arrays

You may simply initialize arrays like below:


Or use the following construct:


This would make “$ar” have the following indices and values:


Same goes for associative arrays:


Or using the following method:


“=>” is a symbol consisting of an equals to “=” and a greater than “>” symbol.

Processing Arrays Using Loops

You can simply process all the elements of an array using the “for loop” as:


Apart from this, there is one other variation of for loop that is designed to process arrays, it is used like:

$ar as $a)

In each iteration element of the array “$ar” gets stored in the variable “$a” which gets printed out by the echo statement. This loop processes all the elements storing different elements of array “$ar” one-by-one into “$a”, in each iteration.

Related Articles:

No comments:

Post a Comment

You are free to comment anything, although you can comment as 'Anonymous' it is strongly recommended that you supply your name. Thank You.

Please don't use abusive language.