Tài liệu Zend PHP Certification Study Guide- P5 ppt

20 320 0
Tài liệu Zend PHP Certification Study Guide- P5 ppt

Đ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

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: <? $a = array (1, 2, 3); $b = $a[1]; // Will return 2 $b = 3; echo $a[1]; // Will print 2 $c = &$a[1]; $c = “test”; echo $a[1]; // Will print “test” ?> 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: <? $array[1] = 1; var_dump ($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) } 05 7090 ch04 7/16/04 8:43 AM Page 64 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 65 Creating Arrays Finally, you can use the array operator to add an element to an array in sequence: <? $array[] = 1; var_dump ($array); ?> 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: <? $array = array ( 10, 20, 30 ); echo count ($array); // outputs 3 ?> 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: <? $array = array ( 10, 20, 30 ); 05 7090 ch04 7/16/04 8:43 AM Page 65 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 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: <? $array = array ( 10, 20, 30 ); $a = array(); list ($a[0], $a[1], $a[2]) = $array; var_dump ($a) ?> 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: 05 7090 ch04 7/16/04 8:43 AM Page 66 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 67 Multidimensional Arrays <? $array = array ( 0 => 10, ‘another array’ => array ( 1 => 11, 2 => 22) ); echo $array[‘another array’][2]; ?> An array that contains only other arrays is referred to as a multidimensional array. For example, <? $array = array ( array ( 10, 20, 30 ), array ( ‘a’, ‘b’, ‘c’ ) ); var_dump ($array); ?> 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: <? $array = array ( 05 7090 ch04 7/16/04 8:43 AM Page 67 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 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: <? $array = array ( 10, 20, 30 ); for ($i = 0; $i < count ($array); $i++) { echo $array[$i] * 10; } ?> 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 05 7090 ch04 7/16/04 8:43 AM Page 68 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 69 Navigating Arrays would be to move the expression count ($array) into a variable before the loop begins: <? $array = array ( 10, 20, 30 ); $count = count ($array); for ($i = 0; $i < $count; $i++) { echo $array[$i] * 10; } ?> 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: <? $array = array ( 10, 5 => 20, 30 ); foreach ($array as $v) { echo $v * 10; } ?> 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: 05 7090 ch04 7/16/04 8:43 AM Page 69 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 70 Chapter 4 Arrays <? $array = array ( 10, 20, 30 ); foreach ($array as $k => $v) { echo “$k = “ . ($v * 10) . “\n”; } ?> 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: <? $array = array ( 10, 20, 30 ); foreach ($array as $k => $v) { $array[$k] = $v * 10; } ?> 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(): 05 7090 ch04 7/16/04 8:43 AM Page 70 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 71 Navigating Arrays <? $array = array ( 10, 20, 30 ); reset ($array); while (list ($k, $v) = each ($array)) { echo “$k = $v\n”; } ?> 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: <? $array = array ( 10, 20, 30 ); 05 7090 ch04 7/16/04 8:43 AM Page 71 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 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: <?php $array = array ( 1 => 10, ‘test’ => ‘a test string’, 200 ); $keys = array_keys ($array); var_dump ($keys); ?> 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) } 05 7090 ch04 7/16/04 8:43 AM Page 72 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 73 Manipulating Keys 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: <?php $array = array ( 1 => 10, ‘test’ => ‘a test string’, 200 ); if (isset ($array[2])) { echo ‘Element 2 is : ‘ . $array[2]; } ?> 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: <?php $array = array ( 1 => 10, ‘test’ => ‘a test string’, 200 ); if (array_key_exists ($array, 2)) { echo ‘Element 2 is : ‘ . $array[2]; } ?> 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. 05 7090 ch04 7/16/04 8:43 AM Page 73 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... the sub-arrays to be sorted as well—independently of each other—you will have to do the honors by hand yourself: < ?php $array = array ( array (11 => 10, 5 => 0, 3 => “a”, 100), array (-1, 30, true, “test”) ); $count = count ($array); for ($i = 0; $i < $count; $i++) { sort ($array[$i]); } ?> PHP offers a function, called array_multisort(), that can come in handy when you want to sort an array in relation... 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(): < ?php $array = array ( 1 => 10, ‘test’ => ‘a test string’, 200 ); echo “Sorting in ascending order: \n”; ksort ($array); Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 05 7090... affect the outcome of a call to ksort() or krsort() For example, Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 75 05 7090 ch04 76 7/16/04 8:43 AM Page 76 Chapter 4 Arrays < ?php $array = array ( 1 => 10, ‘test’ => ‘a test string’, 200 ); echo “Sorting in ascending order: \n”; ksort ($array, SORT_STRING); var_dump ($array); ?> If you execute this script, you will obtain a very... 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 probably be to sort it—there are... 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 maintain the association between keys and values For example, < ?php $array = array ( 1 => 10, ‘test’ => ‘a test string’, Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 05 7090 ch04 7/16/04 8:43 AM Page 77 Manipulating Arrays 200 ); sort... the keys have been completely lost If you want to maintain the associativity of the array, you will have to use asort() (for sorting in ascending order) and arsort() (for sorting in descending order): < ?php $array = array ( 1 => 10, ‘test’ => ‘a test string’, 200 ); asort ($array); var_dump ($array); ?> This will result in the keys being saved and the order being changed as appropriate: array(3) { [“test”]=>...05 7090 ch04 74 7/16/04 8:43 AM Page 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: < ?php $array = array ( 1 => 10, ‘test’ => ‘a test string’, 200 ); $arr_2 = array_change_key_case ($array, CASE_UPPER); var_dump ($arr_2); ?> As you can see, array_change_key_case() returns a copy of the... position as the number 44—array_multisort() is the function for you: Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 05 7090 ch04 7/16/04 8:43 AM Page 79 Manipulating Arrays < ?php $array = array ( array (‘Jack’, ‘John’, ‘Marco’, ‘Daniel’), array (21, 23, 29, 44) ); array_multisort ($array[0], $array[1]); var_dump ($array); ?> This will cause the elements of $array[0]: array(2)... values in the second one will be sorted alphabetically as well: Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 79 05 7090 ch04 80 7/16/04 8:43 AM Page 80 Chapter 4 Arrays < ?php $array = array ( array (‘Jack’, ‘John’, ‘Marco’, ‘Marco’, ‘Daniel’), array (21, 23, 29, 11, 44) ); array_multisort ($array[0], $array[1]); var_dump ($array); ?> This will result in the two values that... 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: < ?php $array = array (‘Jack’, ‘John’, ‘Marco’, ‘Marco’, ‘Daniel’); echo array_rand ($array, 1); ?> In this case, we specified that only one element should be returned; therefore, we’ll receive a single value . which, in turn contain three elements each. Because we didn’t specify any keys, PHP will have created them for us: <? $array = array ( 05 7090 ch04 7/16/04. 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

Ngày đăng: 26/01/2014, 11:20

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