Tải bản đầy đủ (.pdf) (20 trang)

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

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (94.07 KB, 20 trang )

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.
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 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():
<?php
$array = array (
1 => 10,
‘test’ => ‘a test string’,
200
);
echo “Sorting in ascending order: \n”;
ksort ($array);
05 7090 ch04 7/16/04 8:43 AM Page 74
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
75
Manipulating Keys
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,
05 7090 ch04 7/16/04 8:43 AM Page 75
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
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 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,
<?php
$array = array (

1 => 10,
‘test’ => ‘a test string’,
05 7090 ch04 7/16/04 8:43 AM Page 76
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
77
Manipulating Arrays
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):
<?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”]=>
string(13) “a test string”
[1]=>
int(10)
[2]=>
int(200)
}
05 7090 ch04 7/16/04 8:43 AM Page 77
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
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
$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 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:
05 7090 ch04 7/16/04 8:43 AM Page 78
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
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[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:

05 7090 ch04 7/16/04 8:43 AM Page 79
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
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 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)
}
}
05 7090 ch04 7/16/04 8:43 AM Page 80
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
81
Manipulating Arrays
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:
<?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. (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):
<?php
$suits = “CDSH”;
$cards = “A234567890JQK”;
$suit_count = 4;
$card_count = 13;
// Create the deck
$deck = array();
for ($i = 0; $i < $suit_count; $i++)
{
05 7090 ch04 7/16/04 8:43 AM Page 81
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
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:
<?php
$a = array (10, 20, 30, 40);
$b = array (10, 20, 30, 40);
$array = array_merge ($a, $b);
var_dump ($array);
?>
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)
05 7090 ch04 7/16/04 8:43 AM Page 82
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

83
Manipulating Arrays
[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:
<?php
$a = array (‘a’ => 10, 20, 30, 40);
$b = array (‘a’ => 20, 20, 30, 40);
$array = array_merge ($a, $b);
var_dump ($array);
?>
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:
05 7090 ch04 7/16/04 8:43 AM Page 83
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

×