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

Tài liệu PHP and MySQL by Example- P7 doc

50 485 0
Tài liệu đã được kiểm tra trùng lặp

Đ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

Tiêu đề PHP and MySQL by Example
Trường học University of Technology
Chuyên ngành Web Development
Thể loại Textbook
Năm xuất bản 2023
Thành phố Hanoi
Định dạng
Số trang 50
Dung lượng 1,64 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Modifying Arrays Unsetting, Deleting, Adding, and Changing Elements PHP makes it easy to modify both numeric and associative arrays by providing a number of built-in functions to add new

Trang 1

"A stitch in time saves 9",

"Don't put the cart before the horse",

Trang 2

Figure 8.43 Selecting two random elements from an array Output from Example 8.36

Figure 8.44 Refreshing the screen for two more random elements

Shuffling a Numeric Array (Randomizing the Values)

The shuffle() function causes the elements of a numerically indexed array to be randomized It randomizes the values of an associative array, but destroys the keys The function returns boolean TRUE or FALSE See Example 8.37 Prior to PHP 4.2.0, it was necessary to seed the random number generator (give it a different starting point) with

srand(), but now that is done automatically To randomize a selected number of elements of an array, see the

Trang 3

Shuffle the Array

Trang 4

8.2 Modifying Arrays (Unsetting, Deleting, Adding, and Changing Elements)

PHP makes it easy to modify both numeric and associative arrays by providing a number of built-in functions to add new elements, remove existing elements and/or replace those elements with new ones, copy elements from one array to another, to rearrange elements, and so on

8.2.1 Removing an Array and Its Elements

There are a number of built-in functions to remove elements from an array (see Table 8.8)

Table 8.8 Functions That Remove Elements Function

array_pop()

array_shift()

array_splice()

array_unique()

Removing an Entire Array

The unset() function completely removes an array, as though it never existed Setting the element’s value to zero or the null string assumes the element is still there

Format

void unset ( mixed var [, mixed var [, mixed ]] )

Example:

$colors=array("red","green","blue"); unset($colors); // Removes the array

Removing the Last Element of an Array

The array_pop() function removes the last elment of an array and returns it, shortening the array by one element If the array is empty (or is not an array), NULL will be returned This function resets the array pointer after it is used

Format

mixed array_pop ( array &array )

Example:

$animals = ("dog", "cat", "pig", "cow"); $strayed = array_pop($animals); // The

"cow" is removed from the // array, and assigned

echo "Before pop(): ";

1 $names=array("Tom", "Dan", "Steve", "Christian", "Jerry");

2 foreach($names as $val){

echo "<em>$val </em>";

}

Trang 5

3 $popped = array_pop($names); // Remove last element

echo "<br />After pop(): ";

$popped

$namesarray_pop()

Figure 8.46 The last element from an array is removed with pop() Output from Example 8.38

Removing the First Element of an Array

The array_shift() function removes the first element from an array and returns it, decreasing the size of the array

by one element All numerical array keys start at zero and literal keys will not be touched If an array is empty (or is not

an array), NULL will be returned See Example 8.39

Trang 6

and assigned to $shifted_off_color $shifted_off_color = array_shift( $colors);

echo "Before the shift: ";

1 $names=array("Tom", "Dan", "Steve", "Christian", "Jerry");

Trang 7

Removing Duplicate Values from an Array

The array_unique() function removes duplicate values from an array and returns a new array without the

duplicates The array_unique() function first sorts the values treated as strings, then keeps the first key

encountered for every value, and thereafter, ignores any duplicate keys Two elements are considered equal only if they

are identical (same data type, same value); that is, the === operator applies See Example 8.40

Format

array array_unique ( array array )

Example:

unique_values = array_unique(array("apples", "pears",

"apples", "Apples")); // Removes duplicates and returns an array with unique

Trang 8

Figure 8.48 The array_unique() function Output from Example 8.40

8.2.2 Adding Elements to an Array

PHP provides built-in functions to increase the size of an array by allowing you to add elements.(see Table 8.9)

Table 8.9 Array Functions to Add Elements to an Array Function

array_push()

array_splice()

array_unshift()

Adding Elements to the Beginning of an Array

The array_unshift() function prepends one or more elements onto the beginning of an array, increasing the size

of the array by the number of elements that were added It returns the number of elements that were added See Example 8.41

Format

int array_unshift ( array &array, mixed var [, mixed ] )

Example:

$colors=("yellow", "blue", "white");

$added=array_unshift($colors,"red","green"); // "red", "green", "yellow",

echo "Before unshift(): ";

1 $names=array("Tom", "Dan", "Steve", "Christian", "Jerry");

Trang 9

2 foreach($names as $val){

echo "<em>$val </em>";

}

// Add new element to the beginning

3 array_unshift($names, "Willie", "Liz");

echo "<br />After unshift(): ";

Trang 10

Adding Elements to the End of an Array

The array_push() function pushes one or more elements onto the end of array, increasing the size of the array by the number of elements that were added It returns the number of elements that were added See Example 8.42

Format

int array_push ( array &array, mixed var [, mixed ] )

Example:

$colors=("yellow", "blue", "white"); $added = array_push($colors, "red",

"green"); // "yellow", "blue", "white", "red", "green"

echo "Before push(): ";

1 $names=array("Tom", "Dan", "Christian", "Jerry");

Trang 11

Figure 8.50 The array_push() function Output from Example 8.42

Splicing an Array—Removing and Adding Elements

The word splice is often associated with splicing two pieces of rope, film, or DNA strands It means to join Array elements can be removed and then what is left can be joined back together The array_splice() function removes

a portion of the array and joins it back together, possibly replacing the removed values with new ones The first argument is the array, and the second argument is the place in the array (called the offset) where you want the function

to start removing elements Offset 0 is the first position in the array If you are taking elements from the end of the array, the offset starts at a negative number An offset of –1 indicates the end of the array The third, optional argument tells the function how many elements you want to remove If you do not specify a length, splice() removes everything from the offset to the end of the array A fourth optional argument allows you to list the replacement values (Use the built-in count() function to get the length of the array.) The returned values are the elements that were removed

Simply put, splice() removes any number of elements from an array, starting at some position, and lets you replace those elements with new ones if you want to

The next set of examples demonstrate how array_splice() is used to remove and replace elements in an array Figure 8.51 displays the resulting spliced array

Trang 12

Figure 8.51 The splice() function Each numbered example is applied to the original array

Format

array array_splice ( array &input, int offset [, int length [, array replacement]] )

Examples:

1 $foods=array("bread","milk", "eggs", "fruit", "meat");

array_splice($foods, 4); // Removes "meat" 2 $foods=array("bread","milk",

"eggs", "fruit", "meat"); array_splice($foods,0,3); // Removes "bread",

"milk", and "eggs" 3 $foods=array("bread","milk", "eggs", "fruit", "meat"); array_splice($foods, -2); // Removes "fruit" and "meat" 4

$foods=array("bread","milk", "eggs", "fruit", "meat"); array_splice($foods, 0,0, array("fish", "cheese")); // Prepends the array with "fish" and

"cheese" 5 $foods=array("bread","milk", "eggs", "fruit", "meat");

array_splice($foods, -3, 2, "veggies"); // Backs up three from the end,

removes "eggs" and "fruit", // and replaces them with "veggies" 6

$foods=array("bread","milk", "eggs", "fruit", "meat"); array_splice($foods,2 ,count($foods),array("beer","peanuts")); // Removes "eggs", "fruit", and

"meat" and replaces them with // "beer" and "peanuts"

Trang 13

8.2.3 Copying Elements of an Array

The array_slice() Function

In case you get the terms splice and slice confused, think of a splice as joining two pieces of tape or rope together and think of slice as in a slice of bread or a slice of apple pie The array_slice() function extracts a slice (some specified elements) of an array, specified by an offset and the number of elements to extract It returns the specified sequence of elements from the array and resets the key/index values If the boolean argument is set to TRUE, then the index values will not be adjusted

To simplify, the array_slice() function copies elements from one array, and assigns them to another array The array that is being sliced is not changed See Example 8.43

"bread", "milk", and "eggs"; the order of the // keys/index values are preserved

Trang 14

Figure 8.52 The array_slice() function Output from Example 8.43

Trang 15

8.2.4 Combining and Merging Arrays

The array_combine() Function

The array_combine() function returns an array made up of keys and values The keys of the new array are the made up of the values from the first array and the values associated with the new keys are made up of the values from the second array (PHP 5) The function returns FALSE if there are an unequal number of values in either of the arrays used as arguments

$abbrev

$abbrev

$states

Trang 16

Figure 8.53 Combining arrays with keys and values Output from Example 8.44

The array_merge() Function

The array_merge() function joins two or more arrays together to return a single array The values of one array are appended to the end of the previous array

Format

array array_merge ( array array1 [, array array2 [, array ]] )

Example:

$newarray=array_merge($array1, $array2); // Returns one array

If array elements have the same keys, then the key of the first array will be overwritten by the key of the next one If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended

If only one array is given and the array is numerically indexed, the keys get reindexed in order

Merging Numerically Indexed Arrays

Example 8.45 demonstrates the merging of numerically indexed arrays using the array_merge() function

1 $primary=array('red', 'blue', 'yellow');

echo '$primary=array("red", "blue", "yellow")',"<br />";

2 $secondary=array('orange','purple','green');

echo '$secondary=array("orange","purple","green")',"<br />";

echo 'After merging $primary and $secondary',"<br />";

3 $merged=array_merge($primary, $secondary);

print_r($merged);

?>

<pre> </body> </html>

Trang 17

Explanation

$primary

$secondaryarray_merge()

Figure 8.54 Merging two arrays Output from Example 8.45

Merging Associative Arrays

Example 8.46 demonstrates merging associative arrays and removing duplicate keys

Trang 18

overwritten

Figure 8.55 Merging associative arrays Output from Example 8.46

Trang 19

The array_merge_recursive() Function

The array_merge_recursive() function merges two or more arrays recursively

array_merge_recursive() merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one It returns the resulting array

Format

array array_merge_recursive ( array array1 [, array ] )

If you have two associative arrays being merged and their keys are the same but their values are different, the

array_merge_recursive() function will combine the values of both arrays into another array as shown in Example 8.47

If the arrays have the same numeric key, the later value will not overwrite the original value, but it will be appended

array_merge_recursive()

'color'

array_merge_recursive()

Trang 20

Figure 8.56 Merging keys and values Output from Example 8.47

Trang 21

The Union Operator

The union operator joins two arrays: The array on the right side of the operator is joined to the array on the left side of the operator If any of the keys are the same, the keys on the left side of the array will not be overwritten The union operator is demonstrated in Example 8.48 The resulting arrays are shown in Figure 8.57

3 $combo = $colors + $shades;// Join $shades to $colors

Trang 22

Figure 8.57 The union operator Output from Example 8.48

The Equality and Identical Operators

When using the equality operator to compare two arrays, if both keys and values have the same value, they are equal, but the order and data type does not matter To be identical, both the keys and values must be of the same data type, same value, and in the same order See Example 8.49

1 $pets=array('dog', 'cat', 'bird');

2 $animals=array(1=>'cat',0 =>'dog', "2" => 'bird');

3 if ($pets == $animals){ // key-value pairs are equal

echo "\$pets and \$animals are equal.<br />";

Trang 23

order and keys are of the same type */

echo "\$pets and \$animals are identical.<br />"; }

Trang 24

Figure 8.58 Equal or identical? Output from Example 8.49

8.2.6 More Array Functions

PHP 4 introduced more than 30 functions that allow you to manipulate an array in numerous ways Table 8.11 lists of most of the built-in array functions, many of which we described in detail in this chapter See the PHP manual for a complete list

Table 8.11 The Most Common Array Functions Function

Trang 25

Table 8.11 The Most Common Array Functions Function

Trang 26

Table 8.11 The Most Common Array Functions Function

Trang 27

Table 8.11 The Most Common Array Functions Function

Trang 28

Table 8.11 The Most Common Array Functions Function

Trang 29

Table 8.11 The Most Common Array Functions Function

function

8.3 Chapter Summary

8.3.1 What You Should Know

Now that you have finished this chapter you should be able to answer the following questions:

1 How do you create an array and assign values to it?

2 What is the difference between numerically indexed and string indexed arrays?

3 How do you print an array with print_r() and var_dump()?

4 How do you get the size of an array?

5 How do you loop through array elements with the while, for, and foreach looping constructs?

6 How do you create arrays of arrays?

7 How do you use PHP functions to manipulate an array to add or decrease its size?

8 How do you delete an array?

9 How do you create variables from arrays?

10 What is the difference between extract() and list()?

11 How do you sort arrays?

12 How do you combine arrays?

Ngày đăng: 21/01/2014, 09:20