Other Ways of Initializing Arrays in PHP

Other Ways of Initializing Arrays in PHP


We had discussed about Arrays in PHP in the post
Arrays and Array Processing in PHP
. We learnt how we can
simply initialize an array by giving values to different indices or using the
‘array’ construct. Besides those methods there are a few others
that you should know, which is the topic of this post.


Creating Sequential Arrays


There are times when you want to store sequence or pattern of values in an
array. For that task range() function would prove to be very helpful. Suppose
if we want to have an array having ten elements from 1 to 10. We can use the
following tedious method:


$ar[0]=1;


$ar[1]=2;


$ar[2]=3;






$ar
[9]=10;


or the range function like:


$ar=range(1,10);


the above line of code creates an arrays same as the one above.


This function can also be use with the optional third argument to set the step
between values.


Eg.


$ar=range(1,10,2);


//$ar={1,3,5,7,9}


range() function also works with character, so if you want to have an array
with elements ‘a’ to ‘z’, it could be done with the
following one line of code:


$ar=range('a','z');


Loading Values into arrays from Files


PHP supports a method that can be very helpful at times. You can use this method
to load entire file into an array, where ach line in the file becomes a element
in the arrays.


Have a look at the code below:


$ar=file("shout_box.txt");



Now suppose if the file had the following content:


I Like PHP

Second Line

Third Line


Arrays ‘$ar’ would contain:


array(3) { [0]=> string(12"I Like PHP " [1]=> 


string(13"Second Line " [2]=> string(10"Third Line" }


As you can see each line in the file has become an element in the array.


Copying one Array to another


If you have an array whose values you want another array to be initialized
with, you can use the ‘=’ operator. The equal to ‘=’
operator can \copy one array to another.


$ar=array('a','c','eleven');


$ar2=$ar;


//$ar2= array(3) { [0]=> string(1) "a" [1]=> 


//string(1) "c" [2]=> string(6) "eleven" }


Previous Articles:


Check out this stream