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

PHP 5 Recipes A Problem-Solution Approach PHẦN 3 ppt

68 363 0

Đ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

Thông tin cơ bản

Định dạng
Số trang 68
Dung lượng 451,75 KB

Nội dung

How It Works Two floating-point values are defined and added with the bcadd() function using the default scale (3) set by a call to bcscae(). Then the same two values are added, but this time the default scale is overwritten by the third argument. Note how the result is truncated and not rounded. 3.468 3.4 The GMP extension implements a long list of functions (see Table 3-8) that can be used to manipulate large integer values (more than 32 bits). Table 3-8. GMP Functions Name Description gmp_abs Calculates absolute value gmp_add Adds numbers |gmp_and Logical and gmp_clrbit Clears bit gmp_cmp Compares numbers gmp_com Calculates one’s complement |gmp_div_q Divides numbers gmp_div_qr Divides numbers and gets quotient and remainder gmp_div_r Remainder of the division of numbers gmp_div Alias of gmp_div_q() gmp_divexact Exact division of numbers gmp_fact Factorial gmp_gcd Calculates GCD gmp_gcdext Calculates GCD and multipliers gmp_hamdist Hamming distance gmp_init Creates GMP number gmp_intval Converts GMP number to integer gmp_invert Inverse by modulo gmp_jacobi Jacobi symbol gmp_legendre Legendre symbol gmp_mod Modulo operation gmp_mul Multiplies numbers gmp_neg Negates number gmp_or Logical or gmp_perfect_square Perfect square check gmp_popcount Population count 3-6 ■ MATH LIBRARIES114 5092_Ch03_FINAL 8/26/05 9:48 AM Page 114 Name Description gmp_pow Raises number into power gmp_powm Raises number into power with modulo gmp_prob_prime Checks if number is “probably prime” gmp_random Random number gmp_scan0 Scans for 0 gmp_scan1 Scans for 1 gmp_setbit Sets bit gmp_sign Sign of number gmp_sqrt Calculates square root gmp_sqrtrem Square root with remainder gmp_strval Converts GMP number to string gmp_sub Subtracts numbers gmp_xor Logical xor The following is an alternative to base_convert() that works on integers up to 32-bit. The Code <?php // Example 3-6-2.php if (!extension_loaded("gmp")) { dl("php_gmp.dll"); } /*use gmp library to convert base. gmp will convert numbers > 32bit*/ function gmp_convert($num, $base_a, $base_b) { return gmp_strval(gmp_init($num, $base_a), $base_b); } echo "12345678987654321 in hex is: " . gmp_convert('12345678987654321', 10, 16) . "\n"; ?> How It Works This example takes a large integer value and converts it into a hexadecimal representation. The output will look like this: 12345678987654321 in hex is: 2bdc546291f4b1 Note that all the integer values are represented as strings. 3-6 ■ MATH LIBRARIES 115 5092_Ch03_FINAL 8/26/05 9:48 AM Page 115 ■Note Loading the GMP extension as a DLL will work only on Windows systems, and using the dl() func- tion will work only for CLI and Common Gateway Interface (CGI) versions of PHP. For the Unix system, the GMP extension will be built-in or must be loaded as gmp.so. The large integer values are stored internally as resource types. The function gmp_init() takes two parameters, where the first is a string representation and the second is an optional base value if the integer is given in a base value other than 10. The function gmp_strval() can convert a GMP resource to a readable string value. The rest of the functions manipulate one or more large integer values. 3-7. A Static Math Class The math functions in PHP are, for the most part, designed to be used directly as functions and procedures, but with the new object model introduced in PHP 5 it’s possible to create a static Math() class that will act like math classes in other languages such as Java or JavaScript. ■Note It’s always faster to call the functions directly than it is to use classes to wrap around the functions. However, static classes can make function names easier to remember, as they can be defined closer to what is used in other languages. The next example shows how you can create and use a simple static Math() class. Using the static keyword in front of class members and methods makes it possible to use these without instantiating the class. The Code <?php // Example math.php define('RAND_MAX', mt_getrandmax()); class Math { static $pi = M_PI; static $e = M_E; static function pi() { return M_PI; } static function intval($val) { return intval($val); } 3-7 ■ A STATIC MATH CLASS116 5092_Ch03_FINAL 8/26/05 9:48 AM Page 116 static function floor($val) { return floor($val); } static function ceil($val) { return ceil($val); } static function round($val, $decimals = 0) { return round($val, $decimals); } static function abs($val) { return abs($val); } static function floatval($val) { return floatval($val); } static function rand($min = 0, $max = RAND_MAX) { return mt_rand($min, $max); } static function min($var1, $var2) { return min($var1, $var2); } static function max($var1, $var2) { return max($var1, $var2); } } $a = 3.5; echo "Math::\$pi = " . Math::$pi . "\n"; echo "Math::\$e = " . Math::$e . "\n"; echo "Math::intval($a) = " . Math::intval($a) . "\n"; echo "Math::floor($a) = " . Math::floor($a) . "\n"; echo "Math::ceil($a) = " . Math::ceil($a) . "\n"; echo "Math::round(Math::\$pi, 2) = " . Math::round(Math::$pi, 2) . "\n"; echo "Math::abs(-$a) = " . Math::abs(-$a) . "\n"; echo "Math::floatval($a) = " . Math::floatval($a) . "\n"; echo "Math::rand(5, 25) = " . Math::rand(5, 25) . "\n"; echo "Math::rand() = " . Math::rand() . "\n"; echo "Math::min(2, 28) = " . Math::min(3, 28) . "\n"; echo "Math::max(3, 28) = " . Math::max(3, 28) . "\n"; ?> 3-7 ■ A STATIC MATH CLASS 117 5092_Ch03_FINAL 8/26/05 9:48 AM Page 117 How It Works The output from this script is simple but shows how the class is used: Math::$pi = 3.14159265359 Math::$e = 2.71828182846 Math::intval(3.5) = 3 Math::floor(3.5) = 3 Math::ceil(3.5) = 4 Math::round(Math::$pi, 2) = 3.14 Math::abs(-3.5) = 3.5 Math::floatval(3.5) = 3.5 Math::rand(5, 25) = 13 Math::rand() = 1651387578 Math::min(2, 28) = 3 Math::max(3, 28) = 28 The JavaScript Math() class does not implement the intval(), floatval(), and rand() functions, and the round() function does not take a second argument to specify the number of decimals. The following example shows the same code in JavaScript. The Code <html> <! Example math.html > <body> <script language=JavaScript> a = 3.5; document.write('Math.PI = ' + Math.PI + '<br>'); document.write('Math.E = ' + Math.E + '<br>'); document.write('floor(' + a + ') = ' + Math.floor(a) + '<br>'); document.write('ceil(' + a + ') = ' + Math.ceil(a) + '<br>'); document.write('round(Math.PI) = ' + Math.round(Math.PI) + '<br>'); document.write('min(3, 28) = ' + Math.min(3, 28) + '<br>'); document.write('max(3, 28) = ' + Math.max(3, 28) + '<br>'); </script> </body> </html> How It Works Figure 3-3 shows the output in a browser. 3-7 ■ A STATIC MATH CLASS118 5092_Ch03_FINAL 8/26/05 9:48 AM Page 118 Figure 3-3. Using the Math() class in JavaScript Summary This chapter demonstrated how you can use many of the built-in math functions and opera- tors in conjunction with the advantages of a loosely typed language such as PHP to calculate simple but advanced computations. We first covered the basic data types and how PHP handles them when assigning and cal- culating values. Then we discussed the conversion of integers between different base values. Next, we talked about random numbers and how to build functions to generate random values of floating-point or string data types. The next two topics were logarithmic and trigonometric functions. These functions have a wide range of usages, but this chapter concentrated on how you can use them to generate charts and calculate the distance between two points on the earth. Then, we discussed two extensions for handling math on numbers that do not fit into the simple numeric data types of PHP. Finally, we showed how you can create a static math class and use it like you would implement math classes in other languages. Looking Ahead In Chapter 4, Jon Stephens will demonstrate how to use arrays as complex data types in PHP. The chapter will show how you can manipulate arrays, how you can search arrays to find a specific value, and how you can sort and traverse arrays with different methods. 3-7 ■ A STATIC MATH CLASS 119 5092_Ch03_FINAL 8/26/05 9:48 AM Page 119 5092_Ch03_FINAL 8/26/05 9:48 AM Page 120 Working with Arrays If you have worked with PHP 4 or another scripting language, then you have almost certainly worked with arrays—the idea of lists or collections of values is central to programming in gen- eral, and PHP is no exception. If you are not already familiar with arrays, you should flip back to Lee Babin’s Chapter 1 and get up to speed on just what an array is. Here we will just remind you that the simple definition of the word array is “a collection or list of values.” However, when using arrays in PHP, it is important to remember that PHP lumps together two different sorts of constructs under the same name: ordered lists and unordered lists. Ordered lists are often referred to in PHP as indexed arrays, in which each value is referenced by a unique number, and unordered lists (collections) are referred to as associative arrays, in which each value is identified by a unique name (a string value) and the order usually is not important. It is possible in PHP for a single array to contain both indexed and named values. Because of this, you will sometimes find that PHP has two ways of performing certain array-related tasks, depending on whether you need to be mindful of keys and key/value rela- tions, such as when you are populating or adding items to arrays or ordering (sorting) arrays. This duplication can sometimes make working with PHP arrays a bit overwhelming. On the other hand, it also means that PHP has many built-in functions for performing common tasks with arrays, and when you do have to “roll your own,” you will find that you can handle many of these tasks with just a few lines of code. In this chapter, we will cover the following topics: •Creating and populating arrays •Outputting arrays in various user-friendly formats •Adding new elements to and removing them from existing arrays, both singly and in sets •Getting and setting the size or length of an array •Combining arrays •Finding array elements and traversing arrays •Applying functions to arrays •Sorting arrays according to keys, values, and other criteria •Comparing arrays and array elements •Finding combinations and permutations of array elements 121 CHAPTER 4 ■ ■ ■ 5092_Ch04_CMP4 8/26/05 3:02 PM Page 121 Arrays in PHP 5 provide an amazingly huge range of functionality, so we have lots to cover in this chapter. Let’s get started by reviewing how to create arrays and how to get data into them once they have been created and then move on from there. 4-1. Creating Arrays Creating arrays in PHP is quite easy. Both indexed arrays and associative arrays are produced by calling the array() function. The Code $my_array = array(); $pets = array('Tweety', 'Sylvester', 'Bugs', 'Wile E.'); $person = array('Bill', 'Jones', 24, 'CA'); $customer = array('first' => 'Bill', 'last' => 'Jones', 'age' => 24, 'state' => 'CA'); How It Works The simplest way to create an array in PHP is to call array() without any arguments, which creates a new, empty array. You can create an array that is already populated with some ele- ments simply by listing those elements, separated by commas, as arguments to array(). Array elements can be any valid PHP data type, and elements belonging to the same array can be different data types. To create an associative array, list the array’s key/value pairs using the => operator to associate each key with its corresponding value, and separate the key/value pairs from each other with commas. 4-2. Accessing Array Elements To access the elements of an indexed array, just use square brackets ([]) and the number of the element in the array starting with 0 (not 1!) and going from left to right. The Code print "<p>Pet number 1 is named '$pets[0]'.</p>\n"; print "<p>The person's age is $person[2].</p>\n"; print "<p>The customer's age is {$customer['age']}.</p>\n"; Assuming you have defined the $pets, $person, and $customer arrays as shown in recipe 4-1, the previous statements will produce the following output: Pet number 1 is named 'Tweety'. The person's age is 24. 4-1 ■ CREATING ARRAYS122 5092_Ch04_CMP4 8/26/05 3:02 PM Page 122 ■Note The customer's age is 24. In each case, the array element is accessed by using the array’s variable name followed by the index of the desired element in square brackets. Note that you must put associative array keys in quotes; in addition, if you want to use variable interpolation when outputting an element from an associative array, you must surround the variable name with braces, as shown in the last print state- ment of the previous code. 4-3. Creating Multidimensional Arrays As we said earlier, array elements can be any legal PHP data type, even other arrays. This recipe shows some arrays consisting of other arrays, also referred to as multidimensional arrays. To access elements of such arrays, you can use multiple sets of brackets, working your way from the outside in, as shown in the last two statements in the following code. The Code $customers = array( array('first' => 'Bill', 'last' => 'Jones', 'age' => 24, 'state' => 'CA'), array('first' => 'Mary', 'last' => 'Smith', 'age' => 32, 'state' => 'OH'), array('first' => 'Joyce', 'last' => 'Johnson', 'age' => 21, 'state' => 'TX'), ); $pet_breeds = array( 'dogs' => array('Poodle', 'Terrier', 'Dachshund'), 'birds' => array('Parrot', 'Canary'), 'fish' => array('Guppy', 'Tetra', 'Catfish', 'Angelfish') ); printf("<p>The name of the second customer is %s %s.</p>\n", $customers[1]['first'], $customers[1]['last']); printf("<p>%s and %s</p>", $pet_breeds['dogs'][0], $pet_breeds['birds'][1]); The output of these two statements is as follows: The name of the second customer is Mary Smith. Poodle and Canary 4-3 ■ CREATING MULTIDIMENSIONAL ARRAYS 123 5092_Ch04_CMP4 8/26/05 3:02 PM Page 123 [...]... function array_list($array) # save a bit of typing { printf("(%s)\n", implode(', ', $array) ); 50 92_Ch04_CMP4 8/26/ 05 3: 02 PM Page 1 25 4 -5 ■ INITIALIZING AN ARRAY AS A RANGE OR SEQUENCE OF VALUES } $arr1 = range (5, 11); array_list($arr1); # integer start/end $arr2 = range(0, -5) ; array_list($arr2); # count backward $arr3 = range (3, 15, 3) ; # use $step to skip intervals of 3 array_list($arr3); array_list(... < ?php function array_display($array, $pre=FALSE) { $tag = $pre ? 'pre' : 'p'; printf("%s\n", $tag, var_export($array, TRUE), $tag); } 50 92_Ch04_CMP4 8/26/ 05 3: 02 PM Page 133 4-10 ■ APPENDING ONE ARRAY TO ANOTHER $arr1 = array(1, 2, 3) ; $arr2 = array(10, 20, 30 ); $arr3 = array (5, 10, 15, 20); $comb1 = array_merge($arr1, $arr2); $comb2 = array_merge($arr2, $arr1); $comb3 = array_merge($arr3,... consistently 4- 15 Setting an Array’s Size If you need to guarantee that an array has a certain number of elements, you might want to look at a PHP function called array_pad(), whose prototype is as follows: array array_pad(array $input, int $size, mixed $value) 141 50 92_Ch04_CMP4 142 8/26/ 05 3: 02 PM Page 142 4- 15 ■ SETTING AN ARRAY’S SIZE This function takes as its first argument an array whose length... minimal here—using $array as defined previously, if you assign a value to $array['1'], then the value of $array[1] will be updated; if you assign a value to $array['01'], this will create a new element in $array with that value and with the string key '01' 4 -5 Initializing an Array As a Range or Sequence of Values It is often useful to be able to create an array and fill it with a sequence or range... 10. 75, 11. 25 3. 35 , 17. 95, 10. 85, 5. 95, 10. 75, 11. 25 4- 13 Inserting New Values at an Arbitrary Point in an Indexed Array Suppose you are working with this array: $languages = array('German', 'French', 'Spanish'); And suppose because of a change in your application requirements, you need to insert Russian as the second element You might try this: $languages[1] = 'Russian'; But when you output the changed... var_export(), and var_dump() functions to output an array as a tree These are all particularly useful with associative arrays and nested arrays, as they show all keys and values and act recursively The following example shows how you can do this The Code < ?php $customers = array( array('first' => 'Bill', 'last' => 'Jones', 'age' => 24, 'state' => 'CA'), array('first' => 'Mary', 'last' => 'Smith', 'age'... 'z', ) array ( 0 => 1, 1 => 2, 2 => 3, 3 => 'z', ) Of course, you can use array_merge() and the + operator with associative arrays as well, as shown here: < ?php $dogs1 = array('Lassie' => 'Collie', 'Bud' => 'Sheepdog', 'Rin-Tin-Tin' => 'Alsatian'); 50 92_Ch04_CMP4 8/26/ 05 3: 02 PM Page 1 35 4-11 ■ COMPARING ARRAYS $dogs2 = array('Ringo' => 'Dachshund', 'Traveler' => 'Setter'); array_display(array_merge($dogs1,... array_merge($arr3, $arr2, $arr1); array_display($comb1); array_display($comb2); array_display($comb3); ?> Here is the output: array ( 0 => 1, 1 => 2, 2 => 3, 3 => 10, 4 => 20, 5 => 30 , ) array ( 0 => 10, 1 => 20, 2 => 30 , 3 => 1, 4 => 2, 5 => 3, ) array ( 0 => 5, 1 => 10, 2 => 15, 3 => 20, 4 => 10, 5 => 20, 6 => 30 , 7 => 1, 8 => 2, 9 => 3, ) Variations You might have noticed that array_merge() reorders the array’s... changed array, you discover that what you have done is overwrite the second value, and that is not what you want You want the array to contain the values German, Russian, French, and Spanish You can do this by using the array_splice() function, whose prototype is as follows: array array_splice(array $original, int $offset, int $length, array $new) 137 50 92_Ch04_CMP4 138 8/26/ 05 3: 02 PM Page 138 4- 13 ■... < ?php $arr5 = array(1 => 'x', 2 => 'y', 3 => 'z'); array_display(array_merge($arr1, $arr5), TRUE); array_display($arr1 + $arr5, TRUE); ?> Only the first instance of an element with an index matched in the second or subsequent arrays makes it into the result Any elements having a matching index in a subsequent array are dropped, as shown here: array ( 0 => 1, 1 => 2, 2 => 3, 3 => 'x', 4 => 'y', 5 => 'z', . the class is used: Math::$pi = 3. 14 159 2 6 53 59 Math::$e = 2.71828182846 Math::intval (3 .5) = 3 Math::floor (3 .5) = 3 Math::ceil (3 .5) = 4 Math::round(Math::$pi, 2) = 3. 14 Math::abs( -3 .5) = 3 .5 Math::floatval (3 .5) . 3 .5 Math::floatval (3 .5) = 3 .5 Math::rand (5, 25) = 13 Math::rand() = 1 651 38 757 8 Math::min(2, 28) = 3 Math::max (3, 28) = 28 The JavaScript Math() class does not implement the intval(), floatval(), and rand() functions,. ONE ARRAY TO ANOTHER 132 50 92_Ch04_CMP4 8/26/ 05 3: 02 PM Page 132 $arr1 = array(1, 2, 3) ; $arr2 = array(10, 20, 30 ); $arr3 = array (5, 10, 15, 20); $comb1 = array_merge($arr1, $arr2); $comb2 = array_merge($arr2,

Ngày đăng: 12/08/2014, 16:20

TỪ KHÓA LIÊN QUAN