Beginning PHP 5.3 phần 3 docx

85 436 0
Beginning PHP 5.3 phần 3 docx

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

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Chapter 6: Arrays 133 Figure 6-8 How It Works This script demonstrates four different uses of array_splice(), displaying the results in an HTML table. The first example inserts two new elements at the third position in the array, displaying the removed elements, which in this case is an empty array because no elements were removed: print_r( array_splice( $authors, 2, 0, $arrayToAdd ) ); You can read this line as: “At the third position (2), remove zero (0) elements, then insert $arrayToAdd”. The second example demonstrates how to remove and insert elements at the same time: print_r( array_splice( $authors, 0, 2, $arrayToAdd ) ); This code removes two elements from the start of the array (position 0), then inserts the contents of $arrayToAdd at position 0. The third example shows what happens if you omit the third argument: print_r( array_splice( $authors, 1 ) ); c06.indd 133c06.indd 133 9/21/09 9:00:21 AM9/21/09 9:00:21 AM 134 Part II: Learning the Language This code removes all the elements from the second position in the array (position 1) to the end of the array. Finally, the fourth example demonstrates that you don’t have to pass an array as the fourth argument. If you only have one element to add — say, a string value — you can just pass the value. This is because array_splice() automatically casts the fourth argument to an array before using it. So the string “Orwell” gets converted into an array with a single element (“Orwell”) before being added to the array: print_r( array_splice( $authors, 1, 0, “Orwell” ) ); By the way, you’ll have noticed that the script outputs a lot of the more repetitive markup by creating variables to store snippets of markup ( $headingStart, $headingEnd, $rowStart, $nextCell, $rowEnd ). Not only does this make the PHP code more compact and easier to follow, but it makes it easier to change the markup at a later point if needed. Note that, when inserting an array, the keys of the inserted elements aren’t preserved; instead they’re reindexed using numeric keys. So array_splice() isn’t that useful for inserting associative arrays. For example: $authors = array( “Steinbeck”, “Kafka”, “Tolkien” ); array_splice( $authors, 1, 0, array( “authorName” => “Milton” ) ); echo “<pre>”; print_r( $authors ); echo “</pre>”; This code produces the following result: Array ( [0] => Steinbeck [1] => Milton [2] => Kafka [3] => Tolkien ) Notice how the “Milton” element has had its original key (“authorName”) replaced with a numeric key ( 1). Merging Arrays Together If you want to join two or more arrays together to produce one big array, you need the array_merge() function. This function takes one or more arrays as arguments, and returns the merged array. (The original array(s) are not affected.) c06.indd 134c06.indd 134 9/21/09 9:00:21 AM9/21/09 9:00:21 AM Chapter 6: Arrays 135 Here ’ s an example: $authors = array( “Steinbeck”, “Kafka” ); $moreAuthors = array( “Tolkien”, “Milton” ); // Displays “Array ( [0] = > Steinbeck [1] = > Kafka [2] = > Tolkien [3] = > Milton )” print_r( array_merge( $authors, $moreAuthors ) ); Note that array_merge() joins the array elements of the arrays together to produce the final array. This contrasts with array_push() , array_unshift() , and the square bracket syntax, which all insert array arguments as - is to produce multidimensional arrays: $authors = array( “Steinbeck”, “Kafka” ); $moreAuthors = array( “Tolkien”, “Milton” ); array_push( $authors, $moreAuthors ); // Displays “Array ( [0] = > Steinbeck [1] = > Kafka [2] = > Array ( [0] = > Tolkien [1] = > Milton ) )” print_r( $authors ); A nice feature of array_merge() is that it preserves the keys of associative arrays, so you can use it to add new key/value pairs to an associative array: $myBook = array( “title” = > “The Grapes of Wrath”, “author” = > “John Steinbeck”, “pubYear” = > 1939 ); $myBook = array_merge( $myBook, array( “numPages” = > 464 ) ); // Displays “Array ( [title] = > The Grapes of Wrath [author] = > John Steinbeck [pubYear] = > 1939 [numPages] = > 464 )” print_r ( $myBook ); If you add a key/value pair using a string key that already exists in the array, the original element gets overwritten. This makes array_merge() handy for updating associative arrays: $myBook = array( “title” = > “The Grapes of Wrath”, “author” = > “John Steinbeck”, “pubYear” = > 1939 ); $myBook = array_merge( $myBook, array( “title” = > “East of Eden”, “pubYear” = > 1952 ) ); // Displays “Array ( [title] = > East of Eden [author] = > John Steinbeck [pubYear] = > 1952 )” print_r ( $myBook ); c06.indd 135c06.indd 135 9/21/09 9:00:22 AM9/21/09 9:00:22 AM 136 Part II: Learning the Language However, an element with the same numeric key doesn ’ t get overwritten; instead the new element is added to the end of the array and given a new index: $authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” ); $authors = array_merge( $authors, array( 0 = > “Milton” ) ); // Displays “Array ( [0] = > Steinbeck [1] = > Kafka [2] = > Tolkien [3] = > Dickens [4] = > Milton )” print_r ( $authors ); If you want to merge arrays while preserving numeric keys, try the array_replace() function (new to PHP 5.3). For details see http://www.php.net/manual/en/function.array-replace.php. You can also use array_merge() to reindex a single numerically indexed array, simply by passing the array. This is useful if you want to ensure that all the elements of an indexed array are consecutively indexed: $authors = array( 34 = > “Steinbeck”, 12 = > “Kafka”, 65 = > “Tolkien”, 47 = > “Dickens” ); // Displays “Array ( [0] = > Steinbeck [1] = > Kafka [2] = > Tolkien [3] = > Dickens )” print_r( array_merge( $authors ) ); Converting Between Arrays and Strings PHP provides a few functions that let you convert a string to an array, or an array to a string. To convert a string to an array, you can use PHP ’ s handy explode() string function. This function takes a string, splits it into separate chunks based on a specified delimiter string, and returns an array containing the chunks. Here ’ s an example: $fruitString = “apple,pear,banana,strawberry,peach”; $fruitArray = explode( “,”, $fruitString ); After running this code, $fruitArray contains an array with five string elements: “ apple ”, “ pear ”, “ banana ”, “ strawberry ”, and “ peach ”. You can limit the number of elements in the returned array with a third parameter, in which case the last array element contains the whole rest of the string: $fruitString = “apple,pear,banana,strawberry,peach”; $fruitArray = explode( “,”, $fruitString, 3 ); In this example, $fruitArray contains the elements “ apple ”, “ pear ”, and “ banana,strawberry,peach ”. Alternatively, specify a negative third parameter to exclude that many components at the end of the string from the array. For example, using – 3 in the example just shown creates an array containing just “ apple ” and “ pear ”. (The three components “ banana ”, “ strawberry ”, and “ peach ” are ignored.) c06.indd 136c06.indd 136 9/21/09 9:00:22 AM9/21/09 9:00:22 AM Chapter 6: Arrays 137 explode() is often useful when you need to read in a line of comma - or tab - separated data from a file and convert the data to an array of values. Other useful string - to - array functions include preg_split() for splitting based on regular expres- sions (see Chapter 18 ), and str_split() for splitting a string into characters (or into fixed - length character chunks) — see http://www.php.net/manual/en/function.str - split.php for details. If you want to do the opposite of explode() and glue array elements together into one long string, use — you guessed it — implode() . This takes two arguments: the string of characters to place between each element in the string, and the array containing the elements to place in the string. For example, the following code joins the elements in $fruitArray together to form one long string, $fruitString , with each element separated by a comma: $fruitArray = array( “apple”, “pear”, “banana”, “strawberry”, “peach” ); $fruitString = implode( “,”, $fruitArray ); // Displays “apple,pear,banana,strawberry,peach” echo $fruitString; Converting an Array to a List of Variables The final array - manipulation tool you learn about in this chapter is list() . This construct provides an easy way to pull out the values of an array into separate variables. Consider the following code: $myBook = array( “The Grapes of Wrath”, “John Steinbeck”, 1939 ); $title = $myBook[0]; $author = $myBook[1]; $pubYear = $myBook[2]; echo $title . “ < br/ > ”; // Displays “The Grapes of Wrath” echo $author . “ < br/ > ”; // Displays “John Steinbeck” echo $pubYear . “ < br/ > ”; // Displays “1939” It works, but is rather long - winded. This is where list() comes into play. You use it as follows: $myBook = array( “The Grapes of Wrath”, “John Steinbeck”, 1939 ); list( $title, $author, $pubYear ) = $myBook; echo $title . “ < br/ > ”; // Displays “The Grapes of Wrath” echo $author . “ < br/ > ”; // Displays “John Steinbeck” echo $pubYear . “ < br/ > ”; // Displays “1939” Note that list() only works with indexed arrays, and it assumes the elements are indexed consecutively starting from zero (so the first element has an index of 0 , the second has an index of 1 , and so on). c06.indd 137c06.indd 137 9/21/09 9:00:22 AM9/21/09 9:00:22 AM 138 Part II: Learning the Language A classic use of list() is with functions such as each() that return an indexed array of values. For example, you could rewrite the each() example from “ Stepping Through an Array, ” earlier in this chapter, to use list() : $myBook = array( “title” = > “The Grapes of Wrath”, “author” = > “John Steinbeck”, “pubYear” = > 1939 ); while ( list( $key, $value ) = each( $myBook ) ) { echo “ < dt > $key < /dt > ”; echo “ < dd > $value < /dd > ”; } Summary This chapter has introduced you to another important concept: arrays. These are special variables that can store more than one value, and you ’ ll find that you use them all the time in your PHP scripts. First you delved into the anatomy of arrays, and learned the concepts of indexed and associative arrays. Then you learned how to create arrays in PHP, and access array elements using both square brackets and array_slice() . Along the way you learned about a very useful PHP function, print_r() , that you can use to output entire arrays for debugging purposes. Next, you discovered that every PHP array has an internal pointer that references its elements, and you learned how to use this pointer to move through the elements in an array using current() , key() , next() , prev() , end() , and reset() . You also used the handy foreach looping construct to loop through elements in an array. Arrays get really powerful when you start nesting them to produce multidimensional arrays. You studied how to create such arrays, as well as how to access their elements and loop through them. Finally, you explored some of PHP ’ s powerful array - manipulation functions, including: Sorting functions — You looked at functions such as sort() , asort() , ksort() and array_multisort() Functions for adding and removing elements — These include array_unshift() , array_ shift() , array_push() , array_pop() and array_splice() array_merge() – – This function is useful for merging two or more arrays together explode() and implode() — These let you convert between arrays and strings list() – – You can use this to store array elements in a list of individual variables PHP has a lot more array - related functions than the ones covered in this chapter. It ’ s a good idea to explore the online PHP manual at http://www.php.net/types.array to get an overview of the other array functions that PHP has to offer. Also, try the following two exercises to test your array manipulation skills. You can find the solutions to these exercises in Appendix A. The next chapter looks at the concept of functions in PHP, and shows you how to create your own functions and build reusable chunks of code. ❑ ❑ ❑ ❑ ❑ c06.indd 138c06.indd 138 9/21/09 9:00:23 AM9/21/09 9:00:23 AM Chapter 6: Arrays 139 Exercises 1. Imagine that two arrays containing book and author information have been pulled from a database: $authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens”, “Milton”, “Orwell” ); $books = array( array( “title” = > “The Hobbit”, “authorId” = > 2, “pubYear” = > 1937 ), array( “title” = > “The Grapes of Wrath”, “authorId” = > 0, “pubYear” = > 1939 ), array( “title” = > “A Tale of Two Cities”, “authorId” = > 3, “pubYear” = > 1859 ), array( “title” = > “Paradise Lost”, “authorId” = > 4, “pubYear” = > 1667 ), array( “title” = > “Animal Farm”, “authorId” = > 5, “pubYear” = > 1945 ), array( “title” = > “The Trial”, “authorId” = > 1, “pubYear” = > 1925 ), ); Instead of containing author names as strings, the $books array contains numeric indices (keyed on “ authorId “ ) pointing to the respective elements of the $authors array. Write a script to add an “ authorName ” element to each associative array within the $books array that contains the author name string pulled from the $authors array. Display the resulting $books array in a Web page. 2. Imagine you are writing a version of the computer game Minesweeper. Use arrays to create and store a minefield on a 20 x 20 grid. Place ten mines randomly on the grid, then display the grid, using asterisks ( * ) for the mines and periods ( . ) for the empty squares. (Hint: To return a ran- dom number between 0 and 19 inclusive, use rand( 0, 19 ) . ) c06.indd 139c06.indd 139 9/21/09 9:00:23 AM9/21/09 9:00:23 AM c06.indd 140c06.indd 140 9/21/09 9:00:23 AM9/21/09 9:00:23 AM 7 Functions If you ’ ve been following the book up to now, you ’ re already familiar with the concept of functions. You ’ ve used built - in functions such as gettype() for determining the type of a variable, and count() that returns the number of elements in an array. This chapter takes a formal look at functions, and shows why they ’ re so useful. You learn: More about how to call functions How to create your own functions to make your code easier to read and work with All about parameters and arguments — you use these to pass values into your functions — and how to return values from functions. (With these techniques, your functions can communicate with the code that calls them) Variable scope and how to use local, global, and static variables to your advantage How to create anonymous functions, which are useful when you need to create simple, disposable functions Finally, toward the end of the chapter, you get to explore more advanced concepts, such as references — which let a function modify variables that were created in the code that calls it — and recursion, which you can use as an alternative to looping. First, though, it ’ s a good idea to start at the beginning, and look at exactly what a function does. What Is a Function? Generally speaking, a function — also called a subroutine in some other languages — is a self - contained block of code that performs a specific task. You define a function using a special syntax — which you learn about later in this chapter — and you can then call that function from elsewhere in your script. A function often accepts one or more arguments , which are values passed to the function by the code that calls it. The function can then read and work on those arguments. A function may also ❑ ❑ ❑ ❑ ❑ c07.indd 141c07.indd 141 9/21/09 9:00:50 AM9/21/09 9:00:50 AM Part II: Learning the Language 142 optionally return a value that can then be read by the calling code. In this way, the calling code can communicate with the function. You can think of a function as a black box. The code that calls a function doesn ’ t need to know what ’ s inside the function; it just uses the function to get the job done. Why Functions Are Useful Functions are an important part of any programming language, and you ’ ll find yourself using and creating functions in PHP all the time. Functions are useful for a number of reasons: They avoid duplicating code — Let ’ s say you ’ ve written some PHP code to check that an email address is valid. If you ’ re writing a webmail system, chances are you ’ ll need to check email addresses at lots of different points in your code. Without functions, you ’ d have to copy and paste the same chunk of code again and again. However, if you wrap your validation code inside a function, you can just call that function each time you need to check an email address They make it easier to eliminate errors — This is related to the previous point. If you ’ ve copied and pasted the same block of code twenty times throughout your script, and you later find that code contained an error, you ’ ll need to track down and fix all twenty errors. If your code was inside a function, you ’ d only need to fix the bug in a single place Functions can be reused in other scripts — Because a function is cleanly separated from the rest of the script, it ’ s easy to reuse the same function in other scripts and applications Functions help you break down a big project — Writing a big Web application can be intimidating. By splitting your code into functions, you can break down a complex application into a series of simpler parts that are relatively easy to build. (This also makes it easier to read and maintain your code, as well as add more functionality later if needed) Calling Functions If you ’ ve worked through the previous chapters you ’ ve already called quite a few of PHP ’ s built - in functions. To call a function, you write the function name, followed by an opening and a closing parenthesis: functionName() If you need to pass arguments to the function, place them between the parentheses, separating each argument by commas: functionName( argument ) functionName( argument1, argument2 ) ❑ ❑ ❑ ❑ c07.indd 142c07.indd 142 9/21/09 9:00:51 AM9/21/09 9:00:51 AM [...]... calls the function whose name is stored in the element, passing in the value of $degrees converted to radians (using PHP s built-in deg2rad() function), and displays the result Here’s the output from the code: 144 Chapter 7: Functions sin (30 ) = 0.5 cos (30 ) = 0.8660254 037 84 tan (30 ) = 0.57 735 026919 In the real world, variable function calling is often used to dynamically select a function to execute on... previous hello_with_style .php script as follows: Saying hello with style Saying hello with style < ?php function helloWithStyle(... Value < ?php $iterations = 10; 161 Part II: Learning the Language function fibonacci( $n ) { if ( ( $n == 0 ) || ( $n == 1 ) ) return $n; return fibonacci( $n-2 ) + fibonacci( $n-1 ); } for ( $i=0; $i > F< ?php echo $i?> < ?php echo fibonacci( $i )?> < ?php } ?> ... function that returns a value: Normal and bold text Normal and bold text < ?php function makeBold( $text ) { return “$text”;... demonstrates this: Understanding variable scope Understanding variable scope < ?php function $hello $world return } helloWithVariables()... array_unique(), and preg_split() functions Save the script as sort_words_by_length .php in your document root folder, then run it in your browser You should see a page similar to Figure 7-5 Sorting words in a block... variables Here’s an example: Saying hello with style Saying hello with style < ?php function helloWithStyle( $font, $size ) { echo... from within your script, the PHP engine jumps to the start of that function and begins running the code inside it When the function is finished, the engine jumps back to the point just after the code that called the function and carries on from there Here’s a simple example that illustrates this point: ... variable that can be accessed anywhere in your script, whether inside or outside a function Such a variable is called a global variable PHP supports global variables, but if you’re used to other programming languages you’ll find PHP handles globals slightly differently In PHP, all variables created outside a function are, in a sense, global in that they can be accessed by any other code in the script that’s... your function to return a value, you use — you guessed it — PHP s return statement: function myFunc() { // (do stuff here) return value; } value can be any expression, so you can use a literal value (such as 1 or false), a variable name (such as $result), or a more complex expression (for example, $x * 3 / 7) 148 Chapter 7: Functions When the PHP engine encounters the return statement, it immediately . 144c07.indd 144 9/21/09 9:00 :52 AM9/21/09 9:00 :52 AM Chapter 7: Functions 1 45 sin (30 ) = 0 .5 cos (30 ) = 0.8660 254 037 84 tan (30 ) = 0 .57 7 35 0 26919 In the real world, variable function calling is often used. browser. You can see the result in Figure 7 - 3 . Figure 7 -3 c07.indd 149c07.indd 149 9/21/09 9:00 : 53 AM9/21/09 9:00 : 53 AM Part II: Learning the Language 150 As a matter of fact, you can use the. inclusive, use rand( 0, 19 ) . ) c06.indd 139 c06.indd 139 9/21/09 9:00: 23 AM9/21/09 9:00: 23 AM c06.indd 140c06.indd 140 9/21/09 9:00: 23 AM9/21/09 9:00: 23 AM 7 Functions If you ’ ve been following

Ngày đăng: 09/08/2014, 14:21

Từ khóa liên quan

Tài liệu cùng người dùng

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

Tài liệu liên quan