Monday, February 14, 2011

PHP Arrays

These pretzels that I made awhile back seem perfect for today's Array post. Happy Valentine's Day! :-)

Arrays are data structures that hold multiple rows of data, usually of the same type. There are languages (like PHP) which allow you to store elements of different types in the same array. Arrays just like matrices in mathematics can be single or multi-dimensional.

When you declare an array variable in C, the compiler allocates a block of memory to be used by the elements of the array. For example, int numbers[10] declaration will set aside 40 bytes for the numbers array in a 32-bit architecture system. The number inside the square brackets is how you tell the compiler how many elements there are in an array. The first element of the array can be referenced by index zero as in numbers[0]. An index of an array counts from the beginning of the array, indicating the ordinal number of the element. C, C++ indexes start from 0.

If you're going to write any kind of significant PHP application, you are going to use arrays. You'll quickly find that PHP arrays are not like C, C++, or Java arrays - they are much more powerful. They are powerful because they really aren't "arrays" at all, but "ordered maps". An ordered map is a data structure that associates values to keys. PHP arrays are not preallocated with fixed size elements. They can function a lot like C or Java arrays by using numeric keys:

$a[0] = "first";
$a[1] = "second";
$a[2] = "third";

But the keys are not limited to numbers:
$a['apple'] = "red";
$a['grape'] = "green";

And the values can be just about anything, including other arrays:
$a['fruits'] = array("apple","grape","strawberry");
$a['veggies'] = array("cabbage","carrot","lettuce"); 
When you assign arrays within arrays like this, you've created PHP's version of multi-dimensional arrays. You can access elements of this multi-dimensional array by specifying two key values. For example:
echo $a['fruits'][0]; // outputs: apple
  echo $a['veggies'][1]; // outputs:  carrot
You'll run into mult-dimensional arrays when accessing databases. The set of records returned from a query will be in an array. Within that array each element will be an array that represents all the fields of a particular record.

Before you use an array, you should declare it, like this:
$a = array();
(Note however, that if you are getting an array back from a database query, then you don't have to declare it, since the function you called to execute the query will do that for you.)

You can also put some entries into the array as you create it:
$a = array("Mercury","Venus","Earth","Mars");

When you create an array this way, the keys will be numbers starting from zero:
0 => "Mercury",
1 => "Venus",
2 => "Earth",
3 => "Mars"

You can get the same result using the append syntax, which adds a new element at the end of the array, and increments a numeric key value:
$a = array();
$a[] = "Mercury",
$a[] = "Venus",
$a[] = "Earth",
$a[] = "Mars"

If you need the keys to be something other than integers, you can specify them like this:
$a = array("Hottest"=>"Mercury","Hot"=>"Venus","JustRight"=>"Earth","Cold"=>"Mars");

Giving you:
$a["Hottest"] equal to: "Mercury",
$a["Hot"] equal to: "Venus",
$a["Just Right"] equal to: "Earth",
$a["Cold"] equal to: "Mars"


To loop through an array, your best bet is the foreach statement:
foreach ($a as $planet) {
  echo $planet; 
// outputs: Mercury, Venus, Earth, Mars

If you need it, you can also access the key value, with this syntax:
// $temp will be the array element's key.
// $planet will be the array element's value.
  foreach ($a as $temp => $planet) {
    echo "$planet is $temp ";
  // outputs: Mercury is Hottest, Venus is Hot, Earth is Just Right, Mars is Cold

But, you should not think that foreach is the only way to iterate over an array. There are times when you need something else. If you know the array has numeric keys starting from zero, you can write a traditional for loop, looking a lot like C:

for ($i=0; $i<count($a); $i++) {
  echo $a[$i];

Or you can make use of the internal array pointer that PHP maintains for each array. This is especially useful if you have a loop where you might need to process more than one array element on a single pass through the loop:
reset($a);  // reset internal pointer to the first element of array
while ($planet = current($a)) {  // get the current array element.
  echo $planet;
  next($a);  // advance to the next array element.

When the end of the array is reached, current() will return false and the loop will end.


Now that you've got an array, you can use the many PHP array functions to do things with it. Some of the more important of these are:
  • count() - return the number of elements in the array.
  • sort() - sort array elements.
  • in_array() - check to see if a value exists in the array.

Post a Comment