PHP Basics WorkshopDeveloped by: Paul Burney
Arrays and LoopsAn array is a group of several related variables. A loop is typically used to go through an array and do something with the values. To explore this topic, we will setup a small text submission form, sort the output, and do some checking on the data to see whether or not particular words are present. First, we'll create the html form for the user to fill in. You can use any editor to do this. Here's the source:
You can see the actual page at text.html. Let's look at a few of the highlights in this page. The first is the action of this page, text.php3. That means that the web server is going to send the information contained in this form to a page on the server called text.php3 which is in the same folder as the form. The names of the input item is also important. PHP will automatically create a variable with that name and set its value equal to the value that is sent. Now we need to create a PHP page that will handle the data. Of course, this page needs to be named text.php3. The page will take in the data, look at it, and then send it back to the user after sorting and checking it. The source is listed below:
Line 15 takes the variable $text that was sent and breaks it up wherever there is a space and places those pieces into an array called $keywords. Line 17 sorts the $keywords alphabetically. Please note: it does so in typical unix fashion, that is, first upper case, and then lower case. Line 19 counts how many keywords are in the array. Lines 21 begins a loop that will perform code on every element of the array. Lines 23 checks to see if the keyword is dirty or bad. The == operator means "is equal to" (the = operator is used only for assignment of variables) and the || operator means "or". We use parentheses to make the comparisons explicit. If the keyword is bad or dirty, the echo command on line 25 will be sent to the browser. If it isn't, the else part is invoked, line 27, and the echo command on line 29 is invoked instead. You can now see how the page works at text.html. |
|||||