Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 50 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
50
Dung lượng
1,64 MB
Nội dung
Example 8.36.
<html>
<head><title>Random Array of Two Strings</title></head>
<body bgcolor="lightgreen">
<font face="verdana" size="+1">
<?php
1 $sayings=array("An apple a day keeps the doctor away",
"Too many cooks spoil the broth",
"A stitch in time saves 9",
"Don't put the cart before the horse",
);
2 $selection = array_rand($sayings,2);
3 print "${sayings[$selection[0]]}.<br />";
print "${sayings[$selection[1]]}.<br />";
?>
</body>
</html>
Explanation
1
The!array!called!$sayings!is!assigned!a!list!of!strings.
2
The!array_rand()!function!is!given!a!second!argument,!the!number!2,!which!is!the!
number!of!random!items!to!return.!The!array!called!$selection!will!contain!another!
array!of!two!random!key/index!values.
3
The!first!and!second!randomly!selected!strings!are!printed.!The!value!of!$selection[0]!
is!a!random!index!number.!So!is!the!value!of!$selection[1].!By!using!those!array!
elements!as!indexes!for!the!$sayings!array,!a!randomized!string!will!be!returned.!Notice!
the!curly!braces!surrounding!the!$sayings!array.!The!curly!braces!block!the!array!
elements!so!that!the!first!$!applies!to!the!whole!array.!If!you!remove!the!curly!braces,!
you!will!get!an!error.!The!other!way!to!print!this!would!be!to!remove!the!quotes:!!
print $sayings[$selection[1]] . ".<br />";
!
See!Figures!8.43!and!8.44.
!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
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
array_rand() function.
Format
boolean_value = shuffle( array_name );
!
Example:
$numbers = ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); shuffle($numbers);
!
Output:
9 4 6 5 1 3 2 8 7 10
Example 8.37.
<html><head><title>Shuffle the Array</title></head>
<body bgcolor="33FF66">
<div align="center">
<font size="+1">
<h3>
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Shuffle the Array
</h3>
<?php
1 $months=range(1,12);
2 // srand(time());
echo "<b>Before:</b> ", implode(", ", $months), "<br /><br
/>";
3 shuffle($months);
echo "<b>After: </b>", implode(", ", $months), "<br />";
?>
</font>
</div>
</body>
</html>
Explanation
1
An!array!called!$months!is!created.!A!range!of!1!to!12!months!is!created!with!the!range()!
function.
2
It!is!no!longer!necessary!to!seed!the!random!number!generator!with!srand();!that!is,!give!it!
a!random!starting!point.
3
The!shuffle()!function!shuffles!or!randomizes!the!elements!of!the!array,!$months.!See!
Figure!8.45!for!before!and!after!the!shuffle.
!
Figure 8.45. Shuffling an array of months. Output from Example 8.37.
!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
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
What+It+Does
array_pop()
Removes!and!returns!the!last!element!of!an!array
array_shift()
Removes!and!returns!the!first!element!of!an!array
array_splice()
Removes!and/or!replaces!elements!in!an!array
array_unique()
Removes!duplicates!from!an!array
!
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
to $strayed
Example 8.38.
<html><head><title>array_pop()</title></head>
<body bgcolor="cccc99">
<font face="verdana" size="+1">
<?php
echo "Before pop(): ";
1 $names=array("Tom", "Dan", "Steve", "Christian", "Jerry");
2 foreach($names as $val){
echo "<em>$val </em>";
}
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
3 $popped = array_pop($names); // Remove last element
echo "<br />After pop(): ";
4 foreach($names as $val){
echo "<em>$val </em>";
}
echo "<p>$popped was removed from the end of the
array.</p>";
?>
</pre>
</body>
</html>
Explanation
1
The!numeric!array!$names!is!created!and!assigned!a!list!of!values.
2
The!foreach!loop!is!used!to!iterate!through!the!array!and!display!its!values.
3
The!array_pop()!function!removes!the!last!element!of!the!array,!"Jerry".!The!popped!
off!value!is!returned!and!assigned!to!a!variable,!called!$popped.
4
The!$names!array!is!displayed!after!the!last!element!was!removed!with!the!
array_pop()!function.!See!Figure!8.46.
!
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.
Format
mixed array_shift ( array &array )
!
Example:
$colors=array("red", "blue","green", "yellow"); // First element, "red", removed
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
and assigned to $shifted_off_color $shifted_off_color = array_shift( $colors);
Example 8.39.
<html><head><title>array_shift()</title></head>
<body bgcolor="lightblue">
<font face="verdana" size="+1">
<?php
echo "Before the shift: ";
1 $names=array("Tom", "Dan", "Steve", "Christian", "Jerry");
2 foreach($names as $val){
echo "<em>$val </em>";
}
3 $shifted=array_shift($names); // Remove first element
echo "<br />After the shift: ";
4 foreach($names as $val){
echo "<em>$val </em>";
}
5 echo "<p>$shifted was removed.</p>";
?>
</pre>
</body>
</html>
Explanation
1
A!numeric!array!called!$names!is!defined.
2
The!foreach!loop!is!used!to!iterate!through!the!array!and!get!the!individual!
values,!each!one!in!turn,!assigned!to!$val.
3
The!array_shift()!function!removes!and!returns!the!first!element!of!the!
array,!"Tom",!assigned!to!$shifted.
4
The!foreach!loop!is!used!again!to!iterate!through!the!array!showing!that!the!
array!has!been!shortened!by!one!element.!See!Figure!8.47.
5
The!value!returned!from!the!array_shift()!function!is!"Tom",!the!first!
element!in!the!array.!This!value!is!printed.!See!Figure!8.47.
Figure 8.47. Removing the first element of an array with shift(). Output from Example 8.39.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
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
values.
Example 8.40.
<html><head><title>array_unique()</title></head>
<body bgcolor="cccc99">
<font face="verdana" size="+1">
<?php
echo "Before: ";
1 $numbers=array(1, 3, 5, 7, 7, 7, 9, 9, 8);
2 foreach($numbers as $val){
echo "<em>$val </em>";
}
echo "<br />After: ";
3 $numbers=array_unique($numbers); // Remove duplicates
echo '$numbers=<b>array_unique($numbers)i</b><br />';
foreach($numbers as $val){
echo "<em>$val </em>";
}
?>
</pre>
</body>
</html>
Explanation
1
A!numerically!indexed!array!called!$numbers!is!assigned!a!list!of!integers.
2
The!foreach!loop!is!used!to!loop!through!the!array,!$numbers.!The!value!of!each!of!the!
elements!is!printed.
3
Notice!that!there!are!a!number!of!duplicate!values!in!the!array!$numbers.!The!
array_unique!function!returns!an!array!with!duplicates!removed;!that!is,!an!array!of!
unique!values.!See!Figure!8.48.
!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
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
What+It+Does
array_push()
Pushes!a!new!element(s)!onto!the!end!of!the!array
array_splice()
Removes!and/or!adds!elements!to!an!array!at!any!position
array_unshift()
Adds!a!new!element(s)!to!the!beginning!of!the!array
!
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",
"blue", "white"
Example 8.41.
<html><head><title>array_unshift()</title></head>
<body bgcolor="yellow">
<font face="verdana" size="+1">
<?php
echo "Before unshift(): ";
1 $names=array("Tom", "Dan", "Steve", "Christian", "Jerry");
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
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(): ";
foreach($names as $val){
echo "<em>$val </em>";
}
4 echo "<p>Willie and Liz were added to the beginning of the
array.</p>";
?>
</pre>
</body>
</html>
Explanation
1
The!numeric!array!called!$names!is!assigned!five!string!values.
2
The!foreach!loop!is!used!to!iterate!through!the!array!$names.!Each!value!is!printed!as!
the!loop!cycles!through!the!array.
3
The!array_unshift()!function!is!used!to!append!new!elements!to!the!beginning!of!an!
array.!In!this!example,!"Willie"!and!"Liz"!are!prepended!to!the!array!$names.
"Willie"!will!be!assigned!the!index!of!0,!and!all!the!rest!of!the!index!values!will!be!
incremented!accordingly.
4
Figure!8.49!displays!the!array!after!"Willie"!and!"Liz"!are!prepended!with!the!
array_unshift()!function.
!
Figure 8.49. Adding elements to the beginning of an array with unshift(). Output from Example 8.41.
!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
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"
Example 8.42.
<html><head><title>array push()</title></head>
<body bgcolor="lightblue">
<font face="verdana" size="+1">
<?php
echo "Before push(): ";
1 $names=array("Tom", "Dan", "Christian", "Jerry");
2 foreach($names as $val){
echo "<em>$val </em>";
}
3 array_push($names, "Tina", "Donna");// Add two elements
echo "<br />After push(): ";
foreach($names as $val){
echo "<em>$val </em>";
}
4 echo "<p>Tina and Donna were added to the end of the
array.</p>";
?>
</pre>
</body>
</html>
Explanation
1
The!numeric!array!called!$names!is!assigned!four!string!values.
2
The!foreach!loop!is!used!to!iterate!through!the!array!$names.!Each!value!is!printed!as!
the!loop!cycles!through!the!array.
3
The!array_push()!function!is!used!to!append!new!elements!to!the!end!of!an!array.!In!
this!example,!"Tina"!and!"Donna"!are!appended!to!the!array!$names. "Tom"!will!be!
assigned!the!index!of!0,!and!all!the!rest!of!the!index!values!are!incremented!accordingly.
4
Figure!8.50!displays!the!array!after!"Tina"!and!"Donna"!are!appended!to!it!with!the!
array_push()!function.
!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
[...]... recursively (see page 326) Arrays and Strings explode() Splits up a string by a specified delimiter and creates and array of strings (see page 276) implode() Glues the elements of an array together by some delimiter and creates a string (see page 276) join() Same as implode() split() Splits a string into an array by a delimiter expressed as a regular... from the main part of the program PHP starts executing the instructions in the function, and when finished, returns to the main program and picks up where it left off Functions can be used over and over again and thus save you from repetitious programming They are also used to break up a program into smaller modules to keep it better organized and easier to maintain By definition, a function is a block... (see “Function Libraries— Requiring and Including” on page 373) How to Define a Function To define a function, the function keyword is followed by the name of the function, and a set of parentheses The parentheses are used to hold parameters, values that are received by the function The function’s statements are enclosed in curly braces < ?php function bye() { print "Bye, adios, adieu, au revoir "); }... output, and more PHP provides you with a large array of built-in functions to perform common tasks to save you the trouble of writing your own functions As your programs become more sophisticated, you might find that the particular task you need is not handled byPHP or that you want to break your program into smaller units to make it more manageable Then it is time to write your own functions, and this... 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 Example 8.49 Code View: Equality and Identity < ?php 1 $pets=array('dog',... Add "Willie" and "Daniel" to the end of the array f Replace "Paul" with "Andre" g Add "Alisha" to the beginning of the array h Create another array of names i Merge both of your arrays together and display them in sorted order Create a PHP associative array called "student" of key–value pairs The keys are "Name", "ID", "Address", "Major", "Email", and "Phone" The values will be entered by the user in... to Call a Function Once you define a function, you can use it PHP functions are invoked by calling the function; for example, bye() or show_me($a, $b) Calling a function is similar to taking a detour from the main highway you are driving on, and then later returning to the main road again The main highway is analogous to the PHP program, and a function call is analogous to the detour in the road After... warning such as the following, and the parameter remains unset: Warning: Missing argument 3 for calc_mileage() in c:\wamp\www\exemples\ch9functions\calc_mileage .php on line 5 In the analogy of the pocket calculator, you are the caller when you press the buttons, and the internal functions inside the calculator are the receiver Passing by Value When you pass arguments by value, PHP makes a copy of the variable,... 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... 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 .
The!array_rand()!function!is!given!a!second!argument,!the!number!2,!which!is!the!
number!of!random!items!to!return.!The!array!called!$selection!will!contain!another!
array!of!two!random!key/index!values.
3
The!first !and! second!randomly!selected!strings!are!printed.!The!value!of!$selection[0]!
is!a!random!index!number.!So!is!the!value!of!$selection[1]. !By! using!those!array!
elements!as!indexes!for!the!$sayings!array,!a!randomized!string!will!be!returned.!Notice!
the!curly!braces!surrounding!the!$sayings!array.!The!curly!braces!block!the!array!
elements!so!that!the!first!$!applies!to!the!whole!array.!If!you!remove!the!curly!braces,!
you!will!get!an!error.!The!other!way!to!print!this!would!be!to!remove!the!quotes:!!
print.
It!is!no!longer!necessary!to!seed!the!random!number!generator!with!srand();!that!is,!give!it!
a!random!starting!point.
3
The!shuffle()!function!shuffles!or!randomizes!the!elements!of!the!array,!$months.!See!
Figure!8.45!for!before !and! after!the!shuffle.