<? LESSON 5 ?>
Lesson 5   spacerspacer

Arrays/Troubleshooting

An array is an alternative way to store a group of like variables. Instead of naming each and every variable, we can group these variables together, and with the help of the "for" statement, 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.

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 sandwich variables!

Arrays can be created all at one time, in one line:

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

And each item in the array can be accessed by looping through a "for" statement:

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. Arrays 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.

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. Arrays can be accessed by another version of the for loop, called foreach:

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

With the foreach, you do not 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 word, rather than a number. 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, ";
print "a ". $aPicnic['Drink']. " to drink, and a " . $aPicnic['Dessert']. " for dessert!<br></p>";

Array Examples

Below are some example files that help us further understand the nature of arrays. First is the example file as spelled out in the text above:

arrayPractice.php View Code

Next is an example where you can insert values into text boxes and process a postback to the form page, and the items you input (colors, clothes, emotions) are fed back via 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

The last example allows you to explore the "push" and "pop" features of arrays, where you can "push" new values on an array, or "pop" them back off. This can be done at either the beginning or the end of the array:

pushPop.php View Code

Troubleshooting

Now that we are beginning to become dangerous with our code, lets review a few troubleshooting tactics. Before we get into what to do in a specific instance, let's go over a few PHP development ground rules:

  1. Always build and test your pages in small increments. Don't make large changes and expect things to go smoothly!
  2. Back up your working pages. Never risk damage to a working page when making changes.
  3. Make extensive use of documentation, both inside the code, and on a development journal, in your case, the blog.

PHP Error Messages

When you have errors in your code, PHP will attempt to report them to you. The first type of error we get are called parse errors. Parse errors are usually simple typos, like forgetting to add a dollar sign to a variable, or close a quote, or end a line with a semi-colon. PHP will report the type of error, and attempt to give you the line number on which it appears. Note that on this error, and others the line number is the general vicinity of the error, in practice it may be close, but not exactly the line number indicated!

Error messages will be reported one at a time, starting with the parse errors. As you fix the errors, more may be reported. This means you are making progress! Another type of error can be called the expected error. This error frequently occurs when PHP expects to see something, but doesn't get what it expects. PHP will tell you "expected }" and give the line number, for example. This is difficult to troubleshoot, as the line number is FREQUENTLY unrelated, in this case. This is because you may have a curly brace turned the wrong way, for example. PHP looks for the match to an open brace, and when it doesn't find it, it keeps going down the page, sometimes to the bottom, before reporting the error!

Incorrect Or Missing Data

Sometimes you make a mistake inside the code that is not visible when the page is run. Frequently we will need to halt page execution, and print data to the screen, so we can see what is going in our page. To do this, we do what is called print and die.

print "myVar: " . $myVar;
die();

The above example prints a variable to the page and halts execution. No code is run beyond the "die" statement. You can print the contents of any number of variables just before the die statement, to see what the current contents include. You can check your pages in various locations in this manner.

Another trick is tocomment out possible offending code, to narrow down where the mistake can be. Remember to use the larger scale comment tags, /* and */ for this.

Sometimes you will need to view the output of the page, after the page is run. If you have an HTML error, like a missing quote, the HTML could submerge, or no longer be visible, but could show up in the output of your PHP page, when the source is viewed in a browser.

Lastly, if you are making changes to your page, and nothing makes a difference , add a print and die line at the top of the page, and see if the message appears. If it does not, you may be uploading to the wrong directory, or the FTP client may not be updating the page, which CAN HAPPEN with Unix!

At this point you could rename your page and save it elsewhere to see if you can see your page changes. STOP MAKING CHANGES the moment you suspect nothing is working! If you continue making changes, you may be compounding the problem!

PHP Error Reporting Levels

PHP by default shows all error messages. While this is a good thing while you are developing your site, it may be a bad thing in a production environment with live customers! This is because once we have made the site live, we may not want to display our lack of skill, or worse, display error messages that help a hacker determine our database structure and field names.

The level of error reporting is set in the php.ini file. The problem is the settings are global, so if we shut off error reporting for one website, we shut them off for all sites in our server space. The error messages are shut on or off by the setting called "display_errors", which is set to "on" if you wish any errors to be displayed.

Once you have "display_errors" set to "on", you can set the amount and type of errors set with the setting called "error_reporting". This setting accepts a number (no quotes) to indicate the type of errors that will be displayed. For development purposes, the proper setting would be 2047, which shows nearly all errors.

If you want, you can set the errors to be very specific, and can even set the errors on a per page basis. This is a remedy for having production and development websites running side by side on the same server.

Print this Page Back To Top

© 2002 - 2009 newMANIC INC, All rights reserved