intTypePromotion=1
zunia.vn Tuyển sinh 2024 dành cho Gen-Z zunia.vn zunia.vn
ADSENSE

Zend PHP Certification Study Guide- P5

Chia sẻ: Thanh Cong | Ngày: | Loại File: PDF | Số trang:20

105
lượt xem
22
download
 
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Zend PHP Certification Study Guide- P5: Hãy thẳng thừng, Giả sử bạn đang thuê một ai đó để giám sát hệ thống và PHP của bạn có nó thu hẹp xuống để hai ứng cử viên. Một trong những ứng cử viên nói, "Oh yeah, tôi biết tất cả về PHP." Các ứng cử viên khác nói, "Oh yeah, tôi biết tất cả về PHP, tôi đã được thông qua kỳ thi chứng chỉ Zend." câu hỏi tiếp theo của bạn có thể sẽ là "Zend Chứng nhận là gì?" Và các ứng viên nói, "Một công ty chuyên về...

Chủ đề:
Lưu

Nội dung Text: Zend PHP Certification Study Guide- P5

  1. 64 Chapter 4 Arrays Note, however, that if you assign an array element to another variable, the assignment will still happen by value because, even though the array operator returns a reference to the element, the assignment operator will do its job by value: As you can see here, the first assignment does not cause a reference to $a[1] to be placed in $b. Instead, the value of the array element is copied into the variable, and when the latter is modified, the former remains unchanged. If the assignment takes place by reference, however, a change to the variable is also reflected in the array element. The array operator can also be used to create an array by assigning a value to a vari- able as if it were an array: This will result in $array—which was empty at the beginning of the script—to be ini- tialized as an array with one element whose key is 1 and whose value is 1: array(1) { [1]=> int(1) }
  2. Creating Arrays 65 Finally, you can use the array operator to add an element to an array in sequence: Assuming that $array was never defined, it will be reset to an array with one element with a key of 0 and a value of 1.The same notes that apply to the addition of an unkeyed element to an array using the array() construct also apply to using the array operator without specifying a key. Counting the Number of Elements in an Array The simplest way to count the number of elements in an array is to use the count() function: Note that you can’t use count() to determine whether a variable contains an array because it returns 1 for both an array that contains one element and for any other vari- able that is not empty or set to Null. Assigning Values from an Array to Multiple Variables The list() construct makes it possible to assign the values of an array to multiple indi- vidual variables at the same time:
  3. 66 Chapter 4 Arrays list ($a, $b, $c) = $array; echo $a; // prints 10 echo $b; // prints 20 echo $c; // prints 30 ?> This construct works only if the array’s keys are all numeric, sequential, and start from 0. Also, list() works by assigning values starting from the rightmost elements—this is not much of a problem if you’re working with individual variables, but it could produce unexpected results if you’re working with an array: This script will create an array that is probably not ordered the way you’d expect: array(3) { [2]=> int(30) [1]=> int(20) [0]=> int(10) } Multidimensional Arrays As we mentioned at the beginning of this chapter, an array can contain an arbitrary number of elements—including other arrays. When an element of an array is itself an array, it can be accessed directly by append- ing the array operator to the array operator of the container array element:
  4. Multidimensional Arrays 67 An array that contains only other arrays is referred to as a multidimensional array. For example, The resulting array will contain two arrays, which, in turn contain three elements each. Because we didn’t specify any keys, PHP will have created them for us:
  5. 68 Chapter 4 Arrays array ( 10, 20, 30 ), array ( ‘a’, ‘b’, ‘c’ ) ); echo $array[1][0]; // echoes ‘a’ echo $array[0][2]; // echoes 30 ?> Navigating Arrays The operation that is perhaps performed most often on arrays is navigation (or walk- ing)—the performance of a particular set of operations for each of its elements. The simplest way to walk through an array, if you know for sure that it will always contain numeric keys starting from 0, is to simply cycle through it with a simple for loop: In the preceding script, you’ll notice that the $i < count ($array) expression is evalu- ated every time the for loop cycles. However, if the number of elements in the array is invariant, this is quite inefficient because the PHP interpreter is forced to call the count() function every time—and the result is unlikely to change. A better approach
  6. Navigating Arrays 69 would be to move the expression count ($array) into a variable before the loop begins: This results in much better performance—but, remember, only if the number of ele- ments in the array isn’t going to change. Also, remember that you can replace the for loop with an equivalent while loop. Using foreach Another way of cycling through the contents of an array is to use a special construct called foreach, which works regardless of how the array is set up: With this syntax, the $v variable will contain the value of every element at every step of the cycle in the order in which they appear in the array. Optionally, you can also retrieve the key:
  7. 70 Chapter 4 Arrays Although it is very practical—which makes using it extremely tempting—there is one major drawback to this construct: It works by creating a copy of the array and making all its assignments by value.This means two things: First, you can’t change the value of an array element simply by modifying the value variable created by the loop construct at every step. If you want to change the value of an array element, you will have to make sure that you retrieve the key of each element as well and make the change explicitly into the array itself: The second problem is the fact that the entire array must be duplicated can spell disaster for your script’s performance—both in terms of CPU and memory usage, and particu- larly if you’re dealing with a large array that is changed throughout the loop. Using the Internal Pointer The third way to walk through an array is to use an internal pointer that PHP automati- cally assigns to each array.The pointer is reset to the beginning of the array by calling the reset() function. Afterwards, each element can be retrieved by using a combination of list() and each():
  8. Navigating Arrays 71 This is the way list() and each() are most often used together. In reality, each actually returns an array—for example, here’s what will be returned for the first row of $array shown previously: array(4) { [1]=> int(10) [“value”]=> int(10) [0]=> int(0) [“key”]=> int(0) } The advantage of using this mechanism is that, obviously, you don’t have to work on a copy of the array.Therefore, your script’s performance will increase. Using a Callback The last way to walk through an array consists of using a callback function—that is, you let PHP walk through the array and call a function you designate for each element of the array.This is accomplished using the array_walk() function:
  9. 72 Chapter 4 Arrays function printout ($v) { echo “$v\n”; } array_walk ($array, ‘printout’); ?> Manipulating Keys Given the flexibility that PHP provides when assigning keys to the elements of an array, being able to manipulate the former is often as important as manipulating the latter. The keys of an array can be extracted from an array into another array by using the array_keys() function: By calling array_keys(), we cause the interpreter to return an array that contains all the keys of $array in the order in which the respective elements appear in the array itself: array(3) { [0]=> int(1) [1]=> string(4) “test” [2]=> int(2) }
  10. Manipulating Keys 73 Checking if an Element Exists There are at least two ways to directly determine whether an element of an array exists. The simplest is to use is_set: This is simple enough and quite useful whenever you need to access an element of an array (or, for that matter, any variable) and you’re not sure that it’s already been set. Another possibility consists of using the array_key_exists() function: The net effect of using this function instead of isset() is the same—the only difference being that the latter is a language construct and, therefore, probably a bit faster than the former.
  11. 74 Chapter 4 Arrays Changing the Array of Keys The array_change_key_case()function can be used to change the case of an array’s keys: As you can see, array_change_key_case() returns a copy of the original array (which translates in a performance impact if you’re dealing with a large array) whose keys have all been changed to the specified case.The second parameter of the call determines the new case of the keys. CASE_UPPER changes the case to uppercase, whereas CASE_LOWER does the opposite. Sorting an Array by Its Keys As we mentioned at the beginning, there is no predefined relationship between the key of an element and the element’s position in the array.This is not always a desirable situa- tion, however, and you might want to be able to actually ensure that the elements of the array are sorted according to their keys.This can be accomplished by using one of two functions—ksort() and krsort():
  12. Manipulating Keys 75 var_dump ($array); echo “Sorting in descending order: \n”; krsort ($array); var_dump ($array); ?> The ksort() function causes the array to be ordered in ascending order based on its keys: Sorting in ascending order: array(3) { [“test”]=> string(13) “a test string” [1]=> int(10) [2]=> int(200) } krsort(), on the other hand, performs the exact opposite operation, sorting the array in descending order based on its keys: Sorting in descending order: array(3) { [2]=> int(200) [1]=> int(10) [“test”]=> string(13) “a test string” } A number of options can be specified as the last parameter when calling either one of these functions to determine how the sorting is performed: n SORT_REGULAR (default)—Causes the array to be sorted according to the normal rules that apply to comparison operations n SORT_NUMERIC—Causes the comparison operations to be performed as if all the keys were numeric n SORT_STRING—Causes the comparison operations to be performed as if all the keys were strings These flags, which indeed apply to all array sorting operations, can significantly affect the outcome of a call to ksort() or krsort(). For example,
  13. 76 Chapter 4 Arrays If you execute this script, you will obtain a very different result from the one previously because all the keys will be converted to strings and compared as such: array(3) { [1]=> int(10) [2]=> int(200) [“test”]=> string(13) “a test string” } Manipulating Arrays The amount of functions that manipulate arrays in PHP is staggering—a testament to just how powerful and popular these elements of the language are. The most common operation that you will want to perform on an array will proba- bly be to sort it—there are a number of ways that you can go about it. The simplest way to sort is to use the sort() or rsort() functions, which behave in exactly the same way as ksort() and krsort() previously except that the sorting is done on the values of each element rather than on the keys. The only problem with using either one of these functions is that they do not main- tain the association between keys and values. For example,
  14. Manipulating Arrays 77 200 ); sort ($array); var_dump ($array); ?> This script will sort the elements of $array, but the end result might not be what you were expecting: array(3) { [0]=> string(13) “a test string” [1]=> int(10) [2]=> int(200) } As you can see, the keys have been completely lost. If you want to maintain the associa- tivity of the array, you will have to use asort() (for sorting in ascending order) and arsort() (for sorting in descending order): This will result in the keys being saved and the order being changed as appropriate: array(3) { [“test”]=> string(13) “a test string” [1]=> int(10) [2]=> int(200) }
  15. 78 Chapter 4 Arrays Note that all the parameters that could be passed to ksort() and krsort() can also be passed to any of the other sorting functions we have examined this far. Sorting Multidimensional Arrays When dealing with multidimensional arrays, sorting becomes a slightly more complex problem because each of the sub-arrays must also be sorted. If you use any of the sorting functions shown so far on a multidimensional array, only the main array will be sorted— the sub-arrays will remain untouched (and this might be what you’re after). If you want the sub-arrays to be sorted as well—independently of each other—you will have to do the honors by hand yourself: PHP offers a function, called array_multisort(), that can come in handy when you want to sort an array in relation to the contents of another.This function behaves simi- larly to the SQL ORDER BY clause with each array passed to be interpreted as one col- umn in a set of rows. Sounds confusing, doesn’t it? Let’s look at an example. Suppose that you have a list of people and their ages in two arrays: $array = array ( array (‘Jack’, ‘John’, ‘Marco’, ‘Daniel’), array (21, 23, 29, 44) ); If you want to sort the names alphabetically, for example, and maintain the correspon- dence between each element in the first array with each element of the second—so that after the sorting operation, the string Daniel will be in the same position as the number 44—array_multisort() is the function for you:
  16. Manipulating Arrays 79 This will cause the elements of $array[1] to be sorted in the same way as those of $array[0]: array(2) { [0]=> array(4) { [0]=> string(6) “Daniel” [1]=> string(4) “Jack” [2]=> string(4) “John” [3]=> string(5) “Marco” } [1]=> array(4) { [0]=> int(44) [1]=> int(21) [2]=> int(23) [3]=> int(29) } } As you can see, the string Daniel is now first in $array[0], and the value 44 has been moved accordingly. If two values in the first array have the same value, the corresponding values in the second one will be sorted alphabetically as well:
  17. 80 Chapter 4 Arrays This will result in the two values that correspond to Marco to be rearranged according to normal sorting rules: array(2) { [0]=> array(5) { [0]=> string(6) “Daniel” [1]=> string(4) “Jack” [2]=> string(4) “John” [3]=> string(5) “Marco” [4]=> string(5) “Marco” } [1]=> array(5) { [0]=> int(44) [1]=> int(21) [2]=> int(23) [3]=> int(11) [4]=> int(29) } }
  18. Manipulating Arrays 81 You can even specify how the sorting takes place by passing two optional parameters after each array.The first determines how the sorting comparisons are performed (and accepts the same flags as the other sorting operations we have seen), whereas the second one determines whether the sorting is done in ascending (SORT_ASC) or descending (SORT_DESC) order. It’s important to keep in mind that using array_multisort() is not the same as sort- ing an array recursively as we did at the beginning of this section. Randomizing Arrays It’s often useful to extract a random value from an array.This can be accomplished by using the array_rand() function, which returns the index of one or more elements picked at random: In this case, we specified that only one element should be returned; therefore, we’ll receive a single value. (It was 4 in my case, corresponding to the “Daniel” element.) Had we specified more than one element, the result would have been returned as an array of keys. The array_rand() function corresponds a bit to saying “pick a card at random from the deck.”What if, however, you want to shuffle the deck and change the order of the array elements in a random way? That’s where the shuffle() function comes into play. In fact, let’s look at this simple example, which creates an array of cards (each composed of one letter to identify the suit and one character to identify the face itself):
  19. 82 Chapter 4 Arrays for ($j = 0; $j < $card_count; $j++) { $deck[] = $suits{$i} . $cards{$j}; } } var_dump ($deck); // Now shuffle the deck shuffle ($deck); var_dump ($deck); ?> This script starts by creating a deck in which the cards are placed in sequence (for exam- ple; CA, C2, C3, and so on) and then calls the shuffle() function to randomize the order in which the items appear in the array.The output is too long to show here, but you could definitely run a solitaire game just by picking out each element of the shuffled deck in turn. Merging Arrays Another frequently needed array-manipulation feature is merging two or more arrays together.This is done by calling the array_merge() function: This results in the $a and $b arrays being appended to each other in the order in which they appear in the call to array_merge() and being stored in a new array: array(8) { [0]=> int(10) [1]=> int(20) [2]=> int(30) [3]=> int(40)
  20. Manipulating Arrays 83 [4]=> int(10) [5]=> int(20) [6]=> int(30) [7]=> int(40) } As you can see here, the two arrays are simply meshed together, and any values that appear in both arrays are added to the end.This, however, only happens if they have numeric keys—if they are associative elements with string keys, the element in the sec- ond array ends up in the result: The preceding example will print this result: array(7) { [“a”]=> int(20) [0]=> int(20) [1]=> int(30) [2]=> int(40) [3]=> int(20) [4]=> int(30) [5]=> int(40) } As you can see, the value of the ‘a’ element in $b ends up in the result array. If this behavior is not what you’re looking for, you can use array_merge_recursive(), which takes elements with the same string keys and combines them into an array inside the value it returns:
ADSENSE

CÓ THỂ BẠN MUỐN DOWNLOAD

 

Đồng bộ tài khoản
2=>2