1. Trang chủ
  2. » Công Nghệ Thông Tin

PHP 5/MySQL Programming- P33 pot

5 198 0

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

138 P H P 5 /M y S Q L P r o g r a m m i n g f o r t h e A b s o l u t e B e g i n n e r Examining the assoc.php Program Imagine that you want to store a list of capital cities. You could certainly store the cities in an array. However, if your main interest is in the relationship between a state and its capital, it could be difficult to maintain the relationship using arrays. In this particular instance, it would be nice if you could use the name of the state as the array index (the element’s number, or position, within the array) rather than a number. Building an Associative Array Here is the code from assoc.php, which generates the array of state capitals: $stateCap[“Alaska”] = “Juneau”; $stateCap[“Indiana”] = “Indianapolis”; $stateCap[“Michigan”] = “Lansing”; The associative array is just like a normal array, except the index values are strings. Note that the indices must be inside quotation marks. Once you have cre- ated an associative array, it is used much like a normal array. print “Alaska: “; print $stateCap[“Alaska”]; print “<br><br>”; FIGURE 5.5 This page uses associative arrays to relate countries and states to their capital cities. Once again, the array’s index is a quoted string. The associative form is terrific for data like this. In essence, it lets you “look up” the capital city if you know the state name. Building an Associative Array with the array() Function If you know the values you want in your array, you can use the array() function to build an associative array. However, building associative arrays requires a slightly different syntax than the garden variety arrays you encountered in Chapter 4. 139 C h a p t e r 5 B e t t e r A r r a y s a n d S t r i n g H a n d l i n g IN DIZZY-ARRAY If all this associative array talk is making you dizzy, don’t panic. It’s just a new name for something you’re very familiar with. Think about the way HTML attrib- utes work. Each tag has a number of attributes that you can use in any order. For example, a standard button might look like this: <input type = “button” value = “Save the world.”> This button has two attributes. Each attribute is made up of a name/value pair. The keywords type and value are names (or indices, or keys, depending on how you want to think of it) and the terms button and Save the world. are the values associated with those names. Cascading style sheets (CSS) use a different syntax for exactly the same idea. The CSS element indicates a series of modifi- cations to the paragraph tag: p {background-color:red; color:yellow; font-size:14pt} While the syntax is different, the same pattern applies. The critical part of a CSS definition is a list of name/value pairs. Associative arrays naturally pop up in one more place. As information comes into your program from an HTML form, it comes in as an associative array. The name of each element becomes an index, and the value of that form element is translated to the value of the array element. Later in this chapter you see how to take advantage of this. An associative array is simply a data structure used when the name/value rela- tionship is the easiest way to work with some kind of data. 140 P H P 5 /M y S Q L P r o g r a m m i n g f o r t h e A b s o l u t e B e g i n n e r I build the $worldCap array using the array() syntax: $worldCap = array( “Albania”=>”Tirana”, “Japan”=>”Tokyo”, “United States”=>”Washington DC” ); The array() function requires the data when you are building an ordinary array, but doesn’t require specified indices. The function automatically generates each element’s index by grabbing the next available integer. In an associative array, you are responsible for providing both the data and the index. The general format for this assignment uses a special kind of assignment opera- tor. The => operator indicates that an element holds some kind of value. I gener- ally read it as holds, so you can say Japan holds Tokyo. In other words, “Japan” => “Tokyo” indicates that PHP should generate an array element with the index “Japan” and store the value “Tokyo” in that element. You can access the value of this array just like any other associative array: print “Japan: “; print $worldCap[“Japan”]; print “<br><br>”; Using foreach with Associative Arrays The foreach loop is just as useful with associative arrays as it is with vanilla arrays. However, it uses a slightly different syntax. Take a look at this code from the assoc.php page: foreach ($worldCap as $country => $capital){ print “$country: $capital<br>\n”; } // end foreach A foreach loop for a regular array uses only one variable because the index can be easily calculated. In an associative array, each element in the array has a unique index and value. The associative form of the foreach loop takes this into account by indicating two variables. The first variable holds the index. The sec- ond variable refers to the value associated with that index. Inside the loop, you can refer to the current index and value using whatever variable names you des- ignated in the foreach structure. Each time through the loop, you are given a name/value pair. In this example, the name is stored in the variable $country, because all the indices in this array are names of countries. Each time through the loop, $country has a different value. In each iteration, the value of the $capital variable contains the array value cor- responding to the current value of $country. Unlike traditional arrays, you cannot rely on associative arrays to return in any particular order when you use a foreach loop to access array elements. If you need elements to show up in a particular order, call them explicitly. Using Built-In Associative Arrays Associative arrays are extremely handy because they reflect a kind of informa- tion storage very frequently used. In fact, you’ve been using associative arrays in disguise ever since chapter 2, “Using Variables and Input.” Whenever your PHP program receives data from a form, that data is actually stored in a number of associative arrays for you. A variable was automatically created for you by PHP for each form element. However, you can’t always rely on that particular bit of magic. Increasingly, server administrators are turning off this automatic variable creation for secu- rity reasons. In fact, the default setup for PHP is now to have this behavior (with the odd name render_globals) turned off. It’s handy to know how PHP gets data from the form as a good example of asso- ciative arrays. It’s also useful because you may need to know how to get form data without the variables being created explicitly for you. Introducing the formReader.php Program The formReader.php program is actually one of the first PHP programs I ever wrote, and it’s one I use frequently. It’s very handy, because it can take the input from any HTML form and report the names and values of each of the form ele- ments on the page. To illustrate, Figure 5.6 shows a typical Web page with a form. When the user clicks the Submit Query button, formReader responds with some basic diagnostics, as you can see from Figure 5.7. Reading the $_REQUEST Array The formReader.php program does its work by taking advantage of an associative array built into PHP. Until now, you’ve simply relied on PHP to create a variable for you based on the input elements of whatever form calls your program. This TRAP 141 C h a p t e r 5 B e t t e r A r r a y s a n d S t r i n g H a n d l i n g 142 P H P 5 /M y S Q L P r o g r a m m i n g f o r t h e A b s o l u t e B e g i n n e r automatic variable creation is called register_globals. While this is an extremely convenient feature, it can be dangerous, so some administrators turn it off. Even when register_globals is active, it can be useful to know other ways of accessing the information that comes from the form. FIGURE 5.6 This form, which has three basic fields, calls the formReader.php program. FIGURE 5.7 The formReader.php program determines each field and its value. . being created explicitly for you. Introducing the formReader .php Program The formReader .php program is actually one of the first PHP programs I ever wrote, and it’s one I use frequently. It’s. the $_REQUEST Array The formReader .php program does its work by taking advantage of an associative array built into PHP. Until now, you’ve simply relied on PHP to create a variable for you based. Input.” Whenever your PHP program receives data from a form, that data is actually stored in a number of associative arrays for you. A variable was automatically created for you by PHP for each form

Ngày đăng: 07/07/2014, 02:20

Xem thêm: PHP 5/MySQL Programming- P33 pot

Mục lục

    PHP 5 / MySQL Programming for the Absolute Beginner

    Chapter 1: Exploring the PHP Environment

    Chapter 2: Using Variables and Input

    Chapter 3: Controlling Your Code with Conditions and Functions

    Chapter 4: Loops and Arrays

    Chapter 5: Better Arrays and String Handling

    Chapter 6: Working with Files

    Chapter 7: Writing Programs with Objects

    Chapter 8: XML and Content Management Systems

    Chapter 9: Using MySQL to Create Databases

TÀI LIỆU CÙNG NGƯỜI DÙNG

  • Đang cập nhật ...

TÀI LIỆU LIÊN QUAN