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:


$ar[0]=1;


$ar[1]=10;



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.


$temp['jan']=21;


$temp['feb']=23;


$temp['mar']=24;


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:


$ar[0]=1;


$ar[1]=10;


Or use the following construct:


$ar=array(110);


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


$ar[0]=1;


$ar[1]=10;



Same goes for associative arrays:


$ar['mon']=0;


$ar['tue']=2;


Or using the following method:


$ar=array('mon'=>0'tue'=>2);


“=>” 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:


$ar=array(110100100010000);


for(
$i=0$i<5$i++)


    echo 
$ar[$i];


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


$ar=array(110100100010000);


foreach(
$ar as $a)


    echo 
$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:


Check out this stream