Arrays in PHP

When we have many similar elements (like state names, for example) it's much more convenient to keep all of them in one variable. It can be done if such a variable is an array. PHP allows us to use usual arrays indexed with numbers and also string-indexed arrays (we've seen $_REQUEST as an example of such array).

Initialization of an array

The easiest way to create an array in a PHP script is to treat a usual variable as an array during the initialization process. To do that we need to write square brackets after the variable name and put an integer index in it:
$myarr[0] = "first string";
$myarr[1] = "second string";
$myarr[3] = "last string"; 
Running these lines of code we are creating an array $myarr containing three elements with indexes 0, 1, and 3. As a matter of fact, we don't even have to specify the indexes. We can use code like this:
$myarr[] = "first string";
$myarr[] = "second string";
$myarr[] = "last string"; 
and achieve exactly the same result. Please notice that by default PHP starts enumerating indexes from 0. If you want to have different indexes you need to specify them precisely. Doing this we don't need to wary about sequence of the indexes:
$myarr[2] = "first string";
$myarr[7] = "second string";
$myarr[4] = "last string"; 
Code above creates an array with three elements in it and these elements have indexes 2, 4, and 7. We can even combine these two methods, that is, start an array giving indexes to its elements and then make PHP do that:
$myarr[2] = "first string";
$myarr[7] = "second string";
$myarr[] = "last string"; 
In this case PHP interpreter takes the biggest array index and gives the next one to the first non-indexed element. Thus, the code above creates an array with indexes 2, 7, and 8.

If we have an array we can access any of its elements by index echo $myarr[3];. The following example creates three arrays using all the methods describe above and then prints their values with for loops. Please notice that before printing each element we check if this particular element exists using function isset().

Initialization arrays using array() constructor.

Another way to create an array is to use array() constructor. Actually, we just combine several separate assignments into one big assignment:
$myarr = array( "first string", "second string", "last string");
This one line creates an array names $myarr with three elements in it. These elements have indexes 0, 1, and 2. These are the default indexes because we didn't tell the PHP interpreter what indexes we want to use. We can specify the desired indexes even using => notation inside the array constructor:
$myarr = array( 1 => "first strig", 3 => "second string", 17 => "last string");
Thus, we created an three-element array with indexes 1, 3, and 17. Of course, we do not have to specify indexes for each element, we can stop at some point and all the rest elements of the array will be indexed consequently starting with the number following the last index we used. For example, the following code
$myarr = array( 1 => "first strig", 3 => "second string", "last string");
creates an array with indexes 1, 3, and 4.

The following complete example illustrates how we can create an array of all the USA states.

Array indexed with strings

As a matter of fact, we do not have to use only numeric indexes. We can use strings to index elements in an array. For example, it would be easier for us to use state abbreviation instead of numeric indexes in the array of states (or state capitals as in the example below), don't you think? To do this, all we need to do is to use strings instead of numbers when we assign values to an array elements:
$strarray1["ca"] = "Sacramento";
$strarray1["il"] = "Springfield";
$strarray1["az"] = "Phoenix";
We can do exactly the same thing using the => notation in the array() constructor:
$strarray2 = array(  "ca" => "Sacramento", "il" => "Springfield", "az" => "Phoenix");
Please notice that if we use string indexes for elements we can not address these elements with numeric indexes. That is, an attempt to access the first element of the array with $strarray[0] will not return "Sacramento". We also need to remember that these indexes are case-sensitive. We can not access the element with index "ca" using "CA" as an index.

We can use both numeric and string indexes in one array, but one element may have only one index either numeric or string. This example show how to create string indexed array and mixed indexed array.

Moving along an array.

If your array is indexed with numeric indexes the easiest way to go through the array is to use a loop:
$myarr = array(1, 1, 2, 3, 5, 8, 13, 21, 34);
for($i=0;$i<100;$i++)
   if( isset($myarr[$i]) ) echo "$myarr[$i]<br>";
However, to be able to loop through the whole array we need to know how many elements this array contains. There is a special function count() that takes an array as argument and returns the number of elements in the array. So, a better way to rewrite the example above is
$myarr = array(1, 1, 2, 3, 5, 8, 13, 21, 34);
for($i=0;$i<count($myarr);$i++)
   if( isset($myarr[$i]) ) echo "$myarr[$i]<br>";
Unfortunately, this method doesn't work if you indexed your array non-sequentially or with string indexes. In this situation functions current(), key(), next(), prev(), and reset() help us. All of these functions take just one argument name of the array. To understand how these function work we need to imagine that for each array there is a special pointer, which points at some element of the array. The element being pointed is called current element. Initially (immediately after initialization) this pointer points at the very first element initialized in the array. That is, for the array defined like this:
$marr[4] = 12;
$marr[3] = 14;
$marr[9] = 17;
This inner pointer will point at the element with index 4. Actually, elements are put in the array in the order we initialized them. So, element with index 3 would be the second one, and with index 9 would be the last.

These functions can get us the value or the index of the current element or move the pointer somewhere to make another element current:

Let's look at the following example: We created an array, made the inner pointer to point at "Alabama" (the first element), printed the current element, moved the pointer forward two times (to point at "Arizona") and printed the current element.

Using these functions we can print all elements from any array:

reset($states);
do{
  echo key($states) . " => " . current($states) . "<br>"; 
}while( next($states) );
We will run this loop until we reach the last element and do next() one more time. After that pointer points outside of the array. To move along array again use reset() to return the pointer at its original position. See how we can print a state selector using PHP.

Iterating through non-sequential array. Functions each() and list()

. Another way to iterate through a string indexed array or an array indexed non-sequential is to use function each(). This function takes an array as an argument and returns pair (index, value) at the current position of the array. If the position is outside the range it returns false. Please notice that this function returns two elements at once, that it, it actually returns an array. Thus, a way to use it is:
while( $cur_elem = each($USAstates) ){
   echo "State: $cur_elem[1] index: $cur_elem[0]
\n"; }
Although there is a more elegant way to do the same thing. We can use function list(), which takes several variables as arguments and make them look like an array. It is usually are used in the form
list($ind, $elem) = each($myArray)
This code gets both the value and the index the current element of the array and puts them as an array into an array of two variables $ind and $elem. Thus, we have index of the current element in the variable $ind and value of the element in the variable $elem. This script illustrates both ways.

Strings and arrays in PHP

Very often occurs a situation when we need to separate a string into elements. For example, words in a sentence, month, day, and date in a date, columns in a table row. We can easily do that using function explode() if these elements are separated with the same delimiter. This function takes two arguments:
  • the first one is a delimiter string
  • and the second is a string you want to split.
    Returns an array containing the substring of the string between the delimiters as the result. Thats, how we can get day, month, and year from a date:

    Function implode() does completely the opposite job. It takes two arguments. The first one is a delimiter string and the second is an array. implode() returns a string that consists of all elements of the array separated by the delimiter. Thus, the following code

    #myarr = array (1, 1, 2, 3, 5, 8);
    echo implode("-:-", $myarr);
    
    should print out
    1-:-1-:-2-:-3-:-5-:-8

    Some other array functions

    PHP has many functions to work with arrays. Let us shortly describe some of them:
    Here you can find several examples.