Programming in PHP

4.28 (118)

Arrays

Arrays are what are defined as complex data structures. They are used for dealing with large amounts of data which need the same operations performed on them, and need to be moved around as a group. An array is simply a structure / way of holding data.

In many languages, an array is of fixed size, meaning that it can only hold a certain amount of data, of which you have previously defined. It is also common for the whole array to have the same data type, however, in as PHP is dynamically typed, this is not the case. Once we have an array, we can access it's data by using an array index. This is simply a number, or in PHP's case could be a string, that identifies a certain part of the array.

Remember the memory location diagram we initially had? You can loosely say that, that is an array of data. It can be thought of as an array properly if we label it as follows:



This shows that an array is simply a block of memory locations, or data. So we have one variable, followed by another, and another, etc. The whole block is named and this is the reference to the array - the name of the array.



In this representation of the array, you can see how we have an index for each memory location of the array. Each location is numbered from 0 through to the maximum of array minus one (by default). This could be represented in PHP in both of the following ways:

Array Example 1
<?php
$classmates 
= array ('Bob''Jane''Peter''Henry''Jill''Jack');
?>


Array Example 2
<?php
$classmates
[0] = 'Bob';
$classmates[1] = 'Jane';
$classmates[2] = 'Peter';
$classmates[3] = 'Henry';
$classmates[4] = 'Jill';
$classmates[5] = 'Jack';
?>


In these two examples, the array is called $classmates and it holds six separate strings. Each name corresponds to an index in the array, so Bob -> 0. We can later access the name by specifying the index to get the value from. As PHP is dynamically typed and can handle dynamic arrays, the following is valid:

Array Examples
<?php
$classmates
[1] = 'Bob';
$classmates[5] = 'Jane';

$classmates[] = 'Henry';
$classmates['Last'] = 'John'

/* prints out the array to the page */
print_r($classmates);
?>


You may notice something strange, in that we have not used ordinal numbers to index our array, but we have used 1, 5, blank and Last. The blank index will convert into number 6, and the Last index will remain the same. This is not particularly useful if we want to loop through the data, however it does represent PHP's array capabilities. The print_r function is able to print out a representation of the array to the page, so the output is:

Output
Array
(
    [1] => Bob
    [5] => Jane
    [6] => Henry
    [Last] => John
)


Multi-dimensional Arrays


The arrays we have described so far has been single dimension. This means that they can only hold one piece of data for each index. But what if we want to also store the ages and heights of all the classmates? The solution to this is to use multi-dimension arrays. Simply put, arrays of arrays.

As an array is a data type, which holds other data types, it could technically hold an array. So you could have an array, holding an array for each index. You can imagine this as a rectangular block / table of data instead of a line of data:



This is again very simple to create in PHP using the array function or by separately writing out each index and value. This time however, we are going to give the indexes of the second array the names of Age and Height:

Multi-Dimensional Arrays
<?php
$classmates 
= array('Name' => array('Bill''Bob''Jane''Jill'), 
                    
'Age' => array(18201722),
                    
'Height' => array(175183164122));

$classmates['Name'][4] = 'Henry';                    
$classmates['Age'][4] = 25;
$classmates['Height'][4] = 190;

print_r($classmates);
?>


In the script, our indexes are called Name, Age and Height for the outer array, and the inner array (the array for each Name, Age and Height)uses ordinal integers as the index. As we have four sets of data in our array at the start, indexes 0 - 3, we can then specify the next set of data by directly specifying the indexes using the square bracket notation. The first square brackets represents the outer array index, and the second square brackets represent the inner array indexes.

The text indexes are defined using the 'Index Name' => 'Value' notation. Firstly the name of the index is supplied, then the => operator, followed by the data. In this case, the data is another array. Notice that => is not the greater than or equal to operator. This script would output:

Output
Array
(
    [Name] => Array
    (
        [0] => Bill
        [1] => Bob
        [2] => Jane
        [3] => Jill
        [4] => Henry
    )

    [Age] => Array
    (
        [0] => 18
        [1] => 20
        [2] => 17
        [3] => 22
        [4] => 25
    )

    [Height] => Array
    (
        [0] => 175
        [1] => 183
        [2] => 164
        [3] => 122
        [4] => 190
    )

)


There is another type of array called jagged-arrays and these are two or more dimensional arrays where the inner arrays aren't all of the same length. This means that you cannot visualize the array as a rectangle or cube, but as a 'jagged' shape. These are very rarely needed, and thus I will not explain the usage of them, although they just follow the same principle of arrays within arrays.

Accessing Array Elements


Accessing the data you have stored is very simple assuming you know what the indexes are. To get the value you just write the array name followed by the index of the value you want in square brackets:

Accessing Elements
<?php

$classmates 
= array ('Bob''Jane''Jill');
echo 
$classmates[2];
?>


This would output Jill as the indexes start by default at zero instead of one. This example can also be furthered to multi-dimensional arrays:

2D Array Accessing
<?php
$classmates 
= array ('Name' => array ('Bob''Jane''Jill'),
                    
'Age' => array (182023));

echo 
$classmates['Name'][1] . ' is ' $classmates['Age'][1] . ' years old!';
?>


In this example, we have a simple two dimensional array holding the names of people and their respective ages. In order to access the value at a certain point, we must specify both the outer and inner index values. We follow the same process by listing the array name, following the square brackets contain the outer array index first (Name) then the inner array index in another set of square brackets (1). This would print the follow phrase:

Jane is 20 years old!


That's all there is to creating, filling and access array elements. However, these methods do not allow for easy manipulation of all the data in the array. For that we need our friends, loops!
Rate this article: BAD 1 2 3 4 5   GOOD
<<     Page 7 of 10    >>

Build Your Own Database Driven Website Using PHP & MySQL

  • Installation instructions for Windows, Linux and Mac OS X
  • Instantly apply working code examples from the book to your Website
  • Build a working Content Management System from scratch
  • Master MySQL database administration
  • Fully updated for PHP 5

       Download FREESample Chapters Now!

Ads

PHPNerds Newsletter