PHP Arrays 101
 

Feature:Arrays are vital to PHP processing
Credit: Imagenation

Note that in the new PHP 5 version, Command Line operations are so easy to use a lot of the exercises will be just snippets of PHP code that users can cut and paste into PHP 5 and try for themselves. Try running PHP 5 in interactive mode using the -a option. If you do so, don't foget to start the session with    <?php. Also users may want to use an interactive directory, with its own php.ini file set as follows: max_execution_time = 30000
If you do so make sure php.exe is on your path. 


In the world of scripting languages, PHP has one of the most versatile array designs - associative arrays. These arrays are like the Java and Perl Hashes or the JavaScript multidimensional arrays. Each array element in PHP is actually made up of a pair of values, a key field and its associated value. So C/C++ and other classic language programmers will have to break out of the mold in their thinking that a PHP array is a sequence of values indexed by integer numbers. No, an array in PHP is a sequence of tuples or value pairs: "a" => "first letter of alphabet", 666 => "unlucky number",
"boolean" => true, 3.14159 => "near pi", "an embedded array" => array(1,2,3,4).
The following sample PHP 5 interactive command-line session shows PHP arrays as truly being associative tuples:

So if we break it out cleanly, an array in PHP is a series of value pairs or tuples:
  $an_array = array(
     0 => "first value",
     1 => 2,
     "key as string" => 3,
     22 => "string as value, again";
     -33 => true,
    "note switch to variable" => $timer,
    "another array" => array(77, 33, 11),
     7777); //our last entry uses the implied key, -32
Note when we use the var_dump() to dump out and display the values of the three arrays, one hardly gets what one would expect in C or Java for an array. You get a listing of pairs of values from PHP. But even more important is that values on the key or first side of the tuple can be any valid PHP variable, integer, or string. On the value or second side of the tuple any valid PHP variable, number, string, array, or object can be used.Note that on the "key" side it is any integer; on the "value" side any number is permitted. Try the following array definition in PHP interactive command mode:
  $var = "Variable in array";
  $anything_goes = array(1,2, $var=>"some variable", "embed_array"=>array(1,2,3));
  var_dump($anything_goes);
  $var = -123;

//Will the array $anything_goes change values with the change in the variable $var ??
  var_dump($anything_goes);

And all those who did our interactive exercise will discover that the array is not changed when the variable contained in it is later changed. This means that the variable value is assigned on initialization of the array and then the link between, the array and the variable is severed. Just as an additional point, if you store an instance of an object in an array, any change in its property or field values is picked up in the array - this is because the array stores the pointer or handle for the object not any of its values.

So now lets quickly summarize what we know about how arrays work. First, arrays are built up of value pairs: 1 => 8888. Second those value pairs (or tuples for all mathematicians) have two parts. The key or first part can be any integer or string. The second part can be any legitimate PHP variable or constant: 1 => -999, "this is an objectr" => $molly; Now if the user does not provide a first value, PHP will auotomatically provide one, an integer, starting at 0. But if the user has supplied a previous integer, it will increment from there. See the last example in the screenshot above how the $mixed_array's "last" entry has a key of 224. In sum, PHP arrays can work like an ordinary array; but also, as we shall see later, they can do so much more when programmers take advantage of the kay, value pairs.

Accessing Array Values

As we can see from the screenshots above of dumped values in the $mixed_array, accessing the values of the array is not going to be simple, especially in an iterative way using a while or for loop. Yes for the $simple_array the traditional ways work:
  for( $ii = 0; $ii<6; $ii++){
    echo "the value for simple_array".$ii." = ".$simple_array[$ii]."\n";
  }

As does the normal ways of retrieving and assigning values to array elements:
  $simple_array[3] = -44;
  $mixed_array["boolean"] = false;
  $multidim_array[0][1][3] = 481;
  $boolval = $mixed_array["boolean"];
  $dim3 = $multidim_array[0][1][3];

but to access values in mixed arrays that have string keys and values users will need some help especially when iterating through a series of values.. PHP provides the list, each/reset and foreach syntax. Here is how each works.

List - provides a way of assigning array values to several variables in one statement:
  $xx=array(22,11,44);
  list($a, $b, $c) = $xx;
  echo $c;    //this prints 44

  $xx = list($a, $b, $c)    //ERROR - the inverse operation does not work

Each - iterates through an array returning the current value the arrays internal pointer is pointing to. Yes, each array has an internal pointer that initially is set to the first key, value pair in the array. Many array functions use and/or change this internal pointer value. When each() comes to the end of an array it does not wind around and go back to the front of the array, reset() does that ... each() stops and returns false when it finds itself at the end of an array. Thus Each/Reset are often used together. Try the following code in PHP:
   $xx = array( "first"=>323, "second" => -99, "Third" => "99-The end");
   while(list($key, $arrvalue) = each($xx)){
     echo "Key=".$key." and value =".$arrvalue."<br>\n";
   }
   var_dump(each($xx));
   reset($xx);
   var_dump(each($xx));

Foreach - The Foreach command simplifies considerably iterating through the values of an array. There are two forms, the simplest foreach ($an_array as $valueonly)... iterates the value part of the array only. The second form picks up the keys as in foreach ($an_array as $keys => $valueonly)... Here is how the PHP Help manual describes the two usages:

//Simple foreach - these two iterative blocks are equivalent
reset ($arr);
while (list(, $value) = each ($arr)) {
  echo "Value: $value<br>\n";
}

foreach ($arr as $value) {
  echo "Value: $value<br>\n";
}

//Key, value foreach - again these two iterative blocks are equivalent
reset ($arr);
while (list($key, $value) = each ($arr)) {
  echo "Key: $key; Value: $value<br>\n";
}

foreach ($arr as $key => $value) {
  echo "Key: $key; Value: $value<br>\n";
}

Even a quick cursory look at PHP arrays shows they are very rich in functionality going well beyond the traditional Fortran or C/C++ arrays. We have shown here the basic rules for defining and accessing PHP arrays. In the next tutorial we examine some of the richness with a look at functions for sorting, splicing and dicing PHP arrays.

 
Top of Page  Tutorials Home  PHP References  PHP Books
©Imagenation 2000-2004