PHP and MySQL by Example- P7

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

0
49
lượt xem
9
download

PHP and MySQL by Example- P7

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Tham khảo tài liệu 'php and mysql by example- p7', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả

Chủ đề:
Lưu

Nội dung Text: PHP and MySQL by Example- P7

  1. Example 8.36. Random Array of Two Strings
  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 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. Shuffle the Array Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  3. Shuffle the Array 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.
  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 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. array_pop()
  5. 3 $popped = array_pop($names); // Remove last element echo "After pop(): "; 4 foreach($names as $val){ echo "$val "; } echo "$popped was removed from the end of the array."; ?> 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.
  6. and assigned to $shifted_off_color $shifted_off_color = array_shift( $colors); Example 8.39. array_shift() 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.
  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 values. Example 8.40. array_unique() 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.
  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 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. array_unshift()
  9. 2 foreach($names as $val){ echo "$val "; } // Add new element to the beginning 3 array_unshift($names, "Willie", "Liz"); echo "After unshift(): "; foreach($names as $val){ echo "$val "; } 4 echo "Willie and Liz were added to the beginning of the array."; ?> 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.
  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" Example 8.42. array push() 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.
  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. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  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" Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  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 Format array array_slice ( array array, int offset [, int length [, bool preserve_keys]] ) array = array_slice ( array_name, integer offset); array = array_slice ( array_name, integer offset, length); array = array_slice ( array_name, integer offset, length, boolean value);   Example: foods = array("bread", "milk", "eggs", "fruit"); $slice = array_slice ( $foods, 2); // $slice contains "eggs" $slice = array_slice ( $foods, 0, 2); // $slice contains "bread" and "milk" $slice = array_slice ( $foods, -2, 1); // $slice contains "milk" $slice = array_slice ( $foods, 0, 3, TRUE); // $slice contains "bread", "milk", and "eggs"; the order of the // keys/index values are preserved Example 8.43. Code  View:   array_slice()             Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  14. Explanation 1 $names  is  a  numeric  array  intialized  with  a  list  of  strings. 2 The  first  argument  to  the  array_slice()  function  is  the  offset  position,  where   to  start  selecting  elements,  and  the  second  argument  is  the  length  or  number   of  elements  to  copy.  In  this  example,  "Tom", "Dan",  and  "Steve"  are  copied   into  an  array  called  $good_guys. 3 In  this  example,  the  offset  starts  from  the  end  of  the  array.  An  offset  of  –2   means  back  up  two  positions  from  the  end  of  the  array.  Because  a  length  is  not   specified,  the  array_splice()  function  will  copy  the  last  two  elements,   "Christian"  and  "Jerry",  from  the  array  and  assign  them  to  $good_guys. 4 For  output  of  this  example,  see  Figure  8.52. Figure 8.52. The array_slice() function. Output from Example 8.43. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  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. Format array array_combine ( array keys, array values )   Example: $titles=array("President", "Programmer", "Accountant"); $names=array("Bill McClintock", "Pearl White", "Barry Buck"); $new_array = array_combine( $titles, $names); // Returns: "President =>"Bill McClintock, "Programmer"=>"Pearl // White", "Accountant"=>"Barry Buck" Example 8.44. Combining Arrays Combining Arrays Explanation 1 An  numeric  array  called  $abbrev  is  assigned  three  string  values. 2 An  numeric  array  called  $states  is  assigned  three  string  values. 3 The  array_combine()  function  combines  the  two  arrays  so  that  the  values  in   the  first  array  $abbrev  become  the  keys  corresponding  to  the  values  in  the   second  array,  $states.  A  new  array  called  $combined,  an  associative  array  of   key–value  pairs,  is  returned. 4 The  combined  array  is  printed.  The  keys  are  made  up  of  the  first  array,  $abbrev,   and  the  values  from  the  second  array,  $states.  See  Figure  8.53  for  the  output. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  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. Example 8.45. Merging Arrays Merging Arrays
  17. Explanation 1 A  numeric  array,  called  $primary,  is  initialized. 2 A  second  numeric  array,  called  $secondary,  is  initialized  with  three  values. 3 The  array_merge()  function  appends  the  second  array  to  the  first  one.  The  index  values   of  the  second  array  are  incremented  in  the  order  in  which  they  appear  in  the  new   merged  array. 4 The  merged  arrays  are  shown  in  Figure  8.54.   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. Example 8.46. Merging Associative Arrays
  18. 1 $cyclewear1=array('item'=>'jersey', 'color'=>'blue', 'type'=> 'hooded'); 2 $cyclewear2=array('size'=>'large','color'=>'white', 'cost'=>'145'); echo 'After merging $cyclewear1 and $cyclewear2',""; 3 $merged=array_merge($cyclewear1, $cyclewear2); 4 print_r($merged); ?> Explanation 1 An  associative  array  is  initialized  with  key–value  pairs. 2 This  associative  array  has  a  'color'  key,  and  so  does  the  first  one.  When  they  are   merged,  the  value  of  the  'color'  key  in  the  first  array  will  be  overwritten  by  the  value   in  the  second  array. 3 The  second  array,  $cyclewear2,  is  appended  to  the  first  array,  $cyclewear1.  If  the  first   array  and  the  second  array  have  duplicate  keys,  the  duplicate  keys  in  the  first  array  are   overwritten. 4 The  output  is  printed  as  shown  in  Figure  8.55. Figure 8.55. Merging associative arrays. Output from Example 8.46.   Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  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. Example 8.47.      Merging Associative Arrays Merging Associative Arrays Explanation 1 The  associative  array,  $cyclewear1,  contains  key–value  pairs  describing  an  item  called   "jersey". 2 The  associative  array,  $cyclewear2,  contains  more  descriptive  key–value  pairs,  and  also   has  a  'color'  key,  but  with  a  different  value. 3 The  array_merge_recursive()  function  merges  the  two  arrays  and  where  the  key  is  the   same,  creates  an  array  of  values.  The  'color'  key  now  consists  of  an  array  of  colors,   'blue'  and  'white'. 4 After  merging  two  arrays  recursively,  the  new  array  returned  from   array_merge_recursive()  is  printed.  See  Figure  8.56.   Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  20. Figure 8.56. Merging keys and values. Output from Example 8.47.   8.2.5. Array Operators The array operators used to manipulate arrays are listed in Table 8.10. These are the same operators we discussed in Chapter 5, “Operators,” but they are now applied to arrays rather than strings and numbers. Table 8.10. Array Operators Operator Function Meaning $a + $b Union Union  of  $a  and  $b $a == $b Equality TRUE  if  $a  and  $b  have  the  same  key–value  pairs $a === Identity TRUE  if  $a  and  $b  have  the  same  key–value  pairs  in  the  same  order   $b and  of  the  same  types $a != $b Inequality TRUE  if  $a  is  not  equal  to  $b $a $b Inequality TRUE  if  $a  is  not  equal  to  $b $a !== Nonidentity TRUE  if  $a  is  not  identical  to  $b $b   Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Đồng bộ tài khoản