<? Information in Sets with Arrays?>

Arrays

An array is an alternative way to store a set of variables. Instead of naming each and every variable, we can group these variables together, and we can loop through the variables to look for a match to our search, etc. Examples of variables that may be good candidates for arrays could be:

The names of the Presidents

The titles of books you sell

All the items in your store

All the chickens in a henhouse

We use arrays when we don't want to bother naming each variable, or alternatively, because we CAN'T as there may either be too many, or more likely we don't wish to control how many there may ultimately be of any particular variable.

Arrays contain Sets of Items: To imagine an array I think of a deck of cards.  Each card has it's own identity but together they make a set.  Looping through the array is like turning over each card in the deck.

Arrays can Expand: To imagine what an array does I imagine an accordian file folder to store coupons or receipts.  If the folder is empty, it takes up little space.  However the folder can grow as receipts are added.  An array can grow in this way.

Arrays are Flexible: What if I wrote a program that accomodated a total of 10 possible sandwiches in a delicatessen. If the owners came up with a new sandwich, would I have to re-write my code? Not if I created an array to store the sandwiches!

Data Types in Arrays: The type of data that can be stored in an array in PHP is very flexible.  Most languages require one data type for all of the data in an array.  Arrays in PHP can store just about anything in each element (value) of the array, including strings, numbers, objects and even more arrays!  Programmer note: Arrays are technically an ordered map that associates values to keys.  This type of behavior is commonly like a collection in other languages.

Array Syntax: Arrays can be created all at one time, in single line of code:

$aFruit = array("bananas","apples","oranges");

The above array contains 3 strings that identify types of fruit. We can add to, sort or remove items in an array with special PHP array functions

Loops: While an array is a convenient way to store a great deal of data, we may need to take special steps to use them.  We can use the print_r() function to view the contents of an array, but frequently we need to process each item in turn.  To do this we'll use a PHP construct like for to access each item in the array in turn:

for($x = 0; $x < count($aFruit); $x++)
{
    print $aFruit[$x] . "<br>";
}

Note that the array of "fruit" here is accessed by the array "element" number (also called an offset or index), in this case stored in a variable named $x. Arrays naturally start at zero, and count up as each item is added, so a 3 element array gets to the number 2. The items of the array can be accessed in this manner by calling the array, and appending the element number.

While we have 3 cheeses in our array, their indexes are 0,1 and 2. You can also see a function named count() in operation above.  Count above returns the number 3, which identifies the total number of items in the array.  Note the highest number in the array has an offset/index of 2 while the count is 3.  This numerical difference is common to almost all arrays in all languages.  This is why the loop only continues while $x < count($aFruit).

Arrays can also be created one line at a time:

$aCheese = array();
$aCheese[0] = "cheddar";
$aCheese[1] = "swiss";
$aCheese[2] = "limburger";

In this case the array of "cheeses" is created first, but has no elements. The array grows by one, each time an item is added to the array.

Adding to an Existing Array: If we start with the aCheese array as above and we want to add (append) more elements to the end of the array, we can do this:

$aCheese[] = "havarti";
$aCheese[] = "gouda";

Notice there is no integer inside the square brackets.  Although we'll see dedicated functions to work with arrays, this is currently the most efficient way to tack on more items to an array in PHP!

foreach:  PHP has another convenient looping construct, the foreach.  Now we declare a variable name inside the parens to identify the current element in the array:

foreach ($aCheese as $cheese)
{
    print $cheese . "<br>";
}

With  foreach, we don't need to specify the element number of the array at all. A new variable is created inside the foreach ($cheese) and then the new variable is called out for each element of the array.

Associative Arrays: Arrays in PHP can be associative, which means that the element (also called a "key") can be a string, rather than an integer. This can be helpful when we want to easily see what each item of a group of associated variables can contain. Here is an example:

$aPicnic = array('Sandwich'=>'Turkey','Drink'=>'Pop','Dessert'=>'Cupcake');

The array is created with a new symbol, =>, which indicates adding the value (Turkey) to a key (Sandwich), for example. Here the array is accessed using a foreach:

print "<p>My Picnic basket includes: <br />";
foreach($aPicnic as $myKey => $myValue)
{
    print $myKey . ": " . $myValue . "<br />";
}
print "</p>";

This type of array actually makes more sense calling out the key names inside a sentence:

print "<p>In my picnic basket, I have a ". $aPicnic['Sandwich']. " sandwich, ";
tprint "a ". $aPicnic['Drink']. " to drink, and a " . $aPicnic['Dessert'] . " for dessert!<br></p>";

The potential complication to using associative arrays is that we must make sure the string that is the key is unique.  When we were using integers as keys this was taken care of for us.

A Set of Links as an Associative Array: Since an associative array requires a unique string as the key, when we use other things that require unique strings, like web addresses we can create arrays that store links:

$nav1 = array();
$nav1['index.php'] = "Home Page";
$nav1['contact.php'] = "Contact Us!";
$nav1['about_us.php'] = "About Us!";
$nav1['links'] = "Our Favorite Links!";

Once links are stored in this way, with the page as the key and the label the user sees as the value, we can create a function to display our links:

function makeLinks($linkArray)
{
    $myReturn = '<ul class="links">';
    foreach($linkArray as $url => $text)
    {
        $myReturn .= '<li><a href="' . $url . '">' . $text . '</a></li>';    
    }    
    return $myReturn . '</ul>';    
}

Now when we add to the array, the link is automatically added to the page.  This function could be called inside your header include file to place links:

echo makeLinks($nav1);

xxxxxx

Superglobals as Associative Arrays: PHP provides data we can use while programming in the form of arrays as well.  Most of the superglobals like $_POST, $_GET, $_SESSION, $_SERVER and $_COOKIES are presented to use in the form of associative arrays:

print $_POST['FirstName'];

Note the name attribute of the form element in the POST data provides the string that is the key in the associative array. 

Looping A Superglobal Array: We can use a for/each loop to identify or process data in a Superglobal array.  This technique is key to creating a dynamic form, or a form that shrinks or grows dependent upon the needs of the application.  Such a form could serve a shopping cart application, as we don't know how many items a user will elect to enter into their cart.

We used such a construct as the foundation of the reCAPTCHA form handler from the Email Formhandler lesson.  View the following function:

function process_post()
{//loop through POST vars and return a single string
    $myReturn = ''; //set to initial empty value
    foreach($_POST as $varName=> $value)
    {#loop POST vars to create JS array on the current page - include email
        if(is_array($_POST[$varName]))
         {#checkboxes are arrays, and we'll collapse the array to comma separated string!
             $myReturn .= $varName . ": " . implode(",",$_POST[$varName]) . PHP_EOL;
         }else{//not an array, create line
             $myReturn .= $varName . ": " . $value . PHP_EOL;
         }
    }
    return $myReturn;
}

In the above example we are looping through the entire POST Superglobal array and matching name/value pairs of form elements to copy to an email we are constructing.

Above we loop through the entire POST using the name/value pairing of $varName and $value.  Since checkboxes store data as arrays as well (an array inside an array) we test to see if the form element is an array via PHP's is_array() function.  If the element sent is an array (a checkbox with more than one item chosen) we collapse the entire contents of the array to a single string via the implode() function.  This takes a string of values and pushes them into a single string - in our case separated by a comma.

process_post.php: If you wish to build your own form handler using the above example as a foundation, here it is: process_post.php zip file

Arrays & Form Data: We can visualize further how arrays work by playing with the following examples. Each uses a form with and processes the data via sent as a string and then uses the PHP explode() function to split the string upon a special character - in this case the comma. To make this work you can insert values into text boxes and process the postback to the form page, and the items you input (colors, clothes, emotions) are exploded into arrays to create nonsense sentences:

arrayTest.php View Code

The next example displays the "sorting" capabilities of arrays. You input comma separated strings of words, names, etc. and the page demonstrates how PHP can sort and shuffle the arrays that it creates out of the string you entered:

arraySort.php View Code

  

 

Print this Page Back To Top

© 2000- 2012 newMANIC INC, All rights reserved