intTypePromotion=1
zunia.vn Tuyển sinh 2024 dành cho Gen-Z zunia.vn zunia.vn
ADSENSE

PHP and MySQL by Example- P6

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

79
lượt xem
12
download
 
  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- p6', 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- P6

  1. A parse error occurred because single quotes were embedded within double quotes. This can be fixed by concatenating the strings as follows: echo $book['Title'] . "";   or by surrounding the array element with curly braces: echo "{$book['Title']}"   Do not eliminate the quotes around the key as shown here: echo $book[Title];   as PHP will treat the key Title as a constant, not as a string. You might inadvertently use a key value that has been defined somewhere else as a constant to produce the error message “E_NOTICE (undefined constant).” Mixing Elements in an Array The index/key value in an array can be a positive or negative number or a string, and the value associated with it can be a string, a number, another array, and so on. If an index value is not given, PHP provides a numeric index, incrementing the index of the next position in the array by 1. Example 8.7 demonstrates how the index and the value of the elements can be mixed. The output is shown in Figure 8.11. Example 8.7. Using a Negative Index
  2. 4 Although  the  value  'orange'  was  not  explicitly  assigned  an  index,  PHP  will   add  1  to  the  previous  numeric  index  value.  Because  that  index  was  –1,  the   index  for  'orange'  will  be  assigned  0. 5 Here  the  index  is  a  string,  "brown",  associated  with  a  value,  "burnt sienna".   Using  a  string  will  have  no  effect  on  the  numeric  indexes. 6 This  line  is  commented  out,  but  provided  to  demonstrate  the  use  of  curly   braces  when  using  arrays  and  nested  quotes;  that  is,  quotes  within  quotes.   When  an  array  element  is  enclosed  within  a  string  in  double  quotes,  the  curly   braces  allow  the  key  to  be  surrounded  by  single  quotes,  without  causing  a  PHP   error.  Without  the  curly  braces  the  error  is:  Parse  error:  syntax  error,   unexpected  T_ENCAPSED_AND_WHITESPACE,  expecting  T_STRNG  or   TVARIABLE  orT_NUM_STRING  inC:\\wamp\php-­‐  on  line  18 Figure 8.11. Mixed array elements. Output from Example 8.7.   8.1.3. Printing an Array There are a number of ways to print the contents of an array. PHP provides built-in functions to display all of the keys and values, or you can use loops. We discuss the built-in functions first. The print_r() Function The print_r() built-in function displays detailed information about a variable, such as its type, length, and contents. It displays the value of a string, integer, or float. In the case of arrays, print_r() displays all of the elements of an array; that is, the key–value pairs. (Use the HTML tag, to display each element on a separate line; otherwise, the output is displayed on one line.) If you would like to capture the output of print_r() in a variable, set the return parameter to boolean TRUE. The print_r() function can also be useful when debugging a program. Remember that print_r() will move the internal array pointer to the end of the array. Use reset() to bring it back to the beginning. PHP 5 appears to reset the pointer automatically after using print_r(). Example 8.8 demonstrates the print_r() function. The output is shown in Figure 8.12. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  3. Format bool print_r ( mixed expression [, bool return] )   Example: print_r($colors); // Display the contents of the array $list=print_r( $colors, true); // Save the return value in $list reset($colors); // Move internal array pointer to array beginning Example 8.8. The print_r() Function Explanation 1 A  numeric  array  called  $colors  is  created  with  four  elements. 2 An  associative  array  called  $book  is  created  with  key–value  pairs. 3 The  print_r()  function  displays  the  array  in  a  humanly  readable  format,   numeric  indexes  on  the  left  of  the  =>  operator  and  the  value  of  the  elements  on   the  right  side.  Use  the  HTML    tag  to  present  the  array  on  separate  lines;   otherwise  it  will  be  displayed  as  one  long  line. 4 The  print_r()  function  displays  the  associative  array,  key–value  pairs  in  an   easy-­‐to-­‐read  format. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  4. Figure 8.12. Printing an array with the print_r() function. Output from Example 8.8.       Example 8.9. The print_r() Function Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  5. Explanation 1 By  giving  print_r()  an  additional  boolean  argument  of  TRUE,  you  can  capture  the   output  of  print_r()  in  a  variable. 2 The  $display  variable  contains  the  output  of  the  print_r()  function;  that  is,  the   contents  of  the  array.  See  Figure  8.13. 3 The  reset()  function  puts  the  internal  array  pointer  back  at  the  beginning  of  the  array.   The  PHP  manual  suggests  using  this  function  to  reset  the  array  pointer,  but  in  PHP  5  it  is   not  necessary.   Figure 8.13. Saving the output from print_r() in a variable. Output from Example 8.9. The var_dump() Function The var_dump() function displays the array (or object), the number of elements, and the lengths of each of the string values. It also provides output with indentation to show the structure of the array or object. (See Chapter 17, “Objects,” for more on objects.) Example 8.10 demonstrates the var_dump() function. The output is shown in Figure 8.14. Format void var_dump ( mixed expression [, mixed expression [, ...]] )   Example: $states=array('CA' => 'California','MT'=>'Montana','NY'=>'New York'); var_dump($states); // Dumps output in a structured format Example 8.10. The var_dump() Function Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  6. Explanation 1 The  numeric  array,  $colors,  is  assigned  a  list  of  colors. 2 The  associative  array,  $book,  is  assigned  key–value  pairs. 3 The  var_dump()  function  takes  the  name  of  the  array  as  its  argument,  and   displays  the  output  by  first  printing  the  number  of  elements  in  the  array,  index   value,  and  then  the  number  of  characters  in  each  of  the  assigned  string  values   and  its  value.  See  Figure  8.14. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  7. Figure 8.14. Printing an array with the var_dump() function. Output Example 8.10.   8.1.4. Using Loops to Access Array Elements Loops make it easy to step through an array. The for and while loops are useful for numeric arrays where you can determine the size, and starting point of the array is usually 0, incremented by 1 for each element. The best way to loop through an associative array is with the foreach loop, although you can use this loop for numerically indexed arrays as well. The for Loop The for loop can be used to iterate through a numeric array. The initial value of the for loop will be the first index value of the array, which will be incremented each time through the loop until the end of the array is reached. Example 8.11 demonstrates how the for loop is used to view each element of an array. The output is displayed in Figure 8.15. Example 8.11. The for Loop Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  8. Elements Explanation 1 The  numeric  array,  $colors,  is  assigned  a  list  of  colors. 2 The  first  argument  to  the  for  loop,  $i = 0,  sets  the  initial  value  of  $i  to  0,   which  represents  the  first  index  in  the  array.  If  the  index  value,  $i,  is  less  than   the  size  of  the  array  (returned  from  the  count()  function),  the  loop  body  is   entered,  after  displaying  the  color,  the  third  argument  of  the  for  loop  is   executed;  that  is,  increment  the  value  of  $i  by  1. 3 Each  time  through  the  loop,  the  next  element  in  the  $colors  array  is  displayed   in  a  table  cell. Figure 8.15. Using the for loop to loop through an array. Output from Example 8.11.     The while Loop The while loop can be used to iterate through a numeric array as shown in Examples 8.12 and 8.13. By setting the initial value to 0, the loop will iterate from the first element of the array (assuming that the array starts at element zero) until it reaches the end of the array. The count() or sizeof() functions can be used to find the length of the array. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  9. Example 8.12. The while Loop Elements Explanation 1 A  numeric  array  called  $colors  is  created  and  assigned  string  values. 2 Variable,  $i,  set  to  0,  will  be  the  initial  value  in  the  loop,  and  will  used  as  the  array’s   index. 3 The  count()  function  returns  the  number  of  elements  in  the  array.  The  while   expression  tests  that  the  value  of  $i  is  less  than  the  size  of  the  array. 4 The  value  of  $i  will  be  used  as  the  index  value  of  the  array,  $colors.  Each  time  through   the  loop,  the  value  will  be  incremented  by  1.  In  this  example,  the  value  of  the  element,   a  color,  will  be  used  as  the  background  color  for  the  current  row,  and  as  the  text   printed  within  the  table’s  data  cell.  See  Figure  8.16. 5 The  value  of  $i  is  incremented  by  1.  If  you  forget  to  increment  $i,  the  loop  will  go   forever  because  $i  will  always  be  less  than  the  size  of  the  array.   Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  10. Figure 8.16. Using the while loop to iterate through an array. Output from Example 8.12. Example 8.13. Code  View:   Table Colors Colored Rows
  11. 6 $i++; // Increment the value of the loop counter 7 } ?> Explanation 1 An  array  called  $colors  is  assigned  four  color  values. 2 The  variable,  $i,  is  initialized  to  0. 3 The  while  loop  evaluates  the  expression  in  parentheses.  Is  the  value  of  $i  less   than  8?  If  it  is,  the  loop  body  is  entered. 4 The  index  value  of  the  $colors  array  is  divided  by  4  and  the  remainder   (modulus)  is  replaced  as  the  new  index  value. 5 The  first  time  in  the  loop  the  index  is  0.  The  value  $color[0]  is  "orange"  and   will  be  filled  in  the  table  for  a  row  of  5  table  cells.  See  Figure  8.17. 6 The  value  of  $i  is  incremented  by  1.  Next  time  through  the  loop,  $color[1]  is   "lightgreen"  and  that  color  will  fill  a  row  of  table  cells. 7 This  is  the  closing  brace  for  the  while  loop. Figure 8.17. The while loop and arrays. Output from Example 8.13.   The foreach Loop The foreach statement is designed to work with both numeric and associative arrays (works only on arrays). The loop expression consists of the array name, followed by the as keyword, and a user-defined variable that will hold each successive value of the array as the loop iterates. The expression in the foreach statement can include both the key and value as shown in Example 8.14. The foreach loop operates on a copy of the original array. If you change the value of an element of the array, it will only change the copy, not the value in the original. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  12. Format (Numeric Array) foreach ($array_name as $value){ do-something with the element's value; } foreach($array_name as $index=>$value){ do-something with the element's index and value } Example: $suit=("diamond", "spade", "club", "heart"); foreach ( $suit as $card_type){ echo $card_type . ""; // displays: diamond } spade club heart (Associative Array) foreach ($array_name as $key => $variable){ do-something $key and/or $variable; } Example: $courses=("101A"=>"Intro to CS", "200B"=>"Data Structures", "130A"=>"Visual Basic" ); foreach ( $courses as $number=>$class_name){ echo $number . '=>' . $class_name . ""; // displays keys // and values } Example 8.14. Code  View:     The foreach Loop
  13. ); 3 foreach ($colors as $value){// Each value is stored in $value echo "$value "; } echo ""; 4 foreach ($employee as $key => $value){// Associative array echo "employee[$key] => $value"; } ?> Explanation 1 A  numeric  array  of  four  colors  is  defined. 2 An  associative  array  of  four  key–value  pairs  is  defined. 3 The  foreach  loop  is  used  to  iterate  through  each  element  of  the  $colors  array.   The  expression  $colors as $value,  means:  In  the  $colors  array  assign  the   value  of  each  element  to  the  variable  $value,  one  at  a  time,  until  the  array   ends.  Each  value  will  be  displayed  in  turn.  See  Figure  8.18. 4 This  foreach  loop  iterates  through  each  key–value  pair  of  an  associative  array,   called  employee.  The  array  name  is  followed  by  the  as  keyword  and  a  variable   to  represent  the  key,  called  $key,  followed  by  the  =>  operator,  and  a  variable  to   represent  the  value,  called  $value. Figure 8.18. Looping through an array with the foreach loop. Output from Example 8.14.   Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  14. Modifying a Value by Reference with a foreach Loop As of PHP 5, you can easily modify an array’s elements by preceding the value after the as keyword with &. This will assign by reference instead of copying the value; that is, whatever you do to the array while in the loop will change the original array, not a copy of it. Example 8.15. Code  View:   The foreach Loop--Changing Values by Reference Original array Array has been changed Explanation 1 A  variable,  $val,  is  assigned  the  string,"hello". 2 A  numeric  array,  called  $years,  is  assigned  four  numbers. 3 The  print_r()  function  prints  the  original  array.  See  Figure  8.19. 4 In  the  foreach  expression  the  variable  $val  is  used  as  a  reference  to  each  element  of  the   $years  array.  The  &  preceding  the  variable  name  makes  it  a  reference.  Any  changes   made  to  the  value  that  $val  references  will  change  the  original  array. 5 1900  is  added  to  each  value  in  the  array  via  the  reference,  $val. 6 Because  $val  is  a  global  variable  (i.e.,  visible  throughout  the  program),  its  original  value   is  changed  in  the  foreach  loop,  and  the  last  value  assigned  to  it  remains  after  the  loop   exits. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  15. is  changed  in  the  foreach  loop,  and  the  last  value  assigned  to  it  remains  after  the  loop   exits. 7 The  print_r()  function  prints  the  modified  array.  See  Figure  8.19.   Figure 8.19. Modifying values by reference. Output from Example 8.15. 8.1.5. Checking If an Array Exists PHP makes it possible to check to see if an array exists, and to check for the existence of keys, values, or both. See Table 8.2. Table 8.2. Functions to Check for Existence of an Array Function What  It  Does array_key_exists() Checks  if  the  given  key  or  index  exists  in  the  array in_array() Checks  if  a  value  exists  in  an  array is_array() Checks  if  the  variable  is  an  array;  returns  TRUE  or  FALSE   Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  16. Example 8.16 demonstrates how to perform array checks using the functions in Table 8.2. The output is displayed in Figure 8.20. Example 8.16. Code  View:   Checking for Existence of an Array or Element Does it Exist? Explanation 1 A  simple  scalar  variable  called  $country  is  assigned  the  string  "USA". 2 An  associative  array  called  $states  is  assigned  key–value  pairs. 3 The  is_array()  built-­‐in  function  returns  true  if  its  argument  is  an  array,  and   false  if  it  is  not.  $states  is  not  an  array. 4 The  array_key_exists()  built-­‐in  function  returns  true  if  its  argument  is  the   key  or  index  in  an  array. 5 The  in_array()  built-­‐in  function  returns  true  if  its  argument  is  a  value  that   exists  in  an  array.  The  array  value  "Montana"  does  exist  in  the  $states   associative  array. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  17. Figure 8.20. Checking an array’s existence.     8.1.6. Creating Strings from Arrays and Arrays from Strings In Chapter 6, “Strings,” we discussed strings and their many functions. Now that we have learned about arrays, PHP provides functions that serve the dual purpose of creating arrays from strings and strings from arrays (see Table 8.3). Table 8.3. Arrays and Strings Function What  It  Does explode() Splits  up  a  string  by  a  specified  delimiter  and  creates  an  array  of  strings implode() Creates  a  string  by  gluing  together  array  elements  by  a  specific  separator join() Alias  for  implode() split() Splits  up  a  string  into  an  array  by  a  regular  expression  (see  Chapter  12,  “Regular   Expressions  and  Pattern  Matching”)   The implode() Function The implode() function creates a string by joining together the elements of an array with a string delimiter, called the glue string. As of PHP 4.3.0, the glue parameter of implode() is optional and defaults to the empty string(""). Another name for implode() is its alias, join(). The implode() function returns a string containing a string representation of all the array elements in the same order, with the glue string between each element. Format string implode ( string glue, array elements )   Example: $stats_array = array('name', 'ssn', 'phone'); // implode() creates a string from an array $stats_string = implode(",", $array); The explode() Function The explode() function splits up a string and creates an array, the opposite of implode(). The new array is created by splitting up the original string into substrings based on the delimiter given. The delimiter is what you determine is the word separator, such as a space or comma. If given a limit, the new array will be limited to that many substrings, and the last one will contain the rest of the string. See also “The preg_split() Function—Splitting Up Strings” on page 510. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  18. Example 8.17 demonstrates how the explode function works. Its output is displayed in Figure 8.21. Format array explode(string separator, string string [, int limit])   Example: $fruit = explode(" ", "apples pears peaches plums") //Creates a 4-element array $fruit = explode("|", "apples|pears|peaches|plums",3) echo $fruit[0], $fruit[1], $fruit[2]; // Creates a 3-element array Example 8.17. explode() Array
  19. Figure 8.21. Converting a string to an array with the explode() function. Output from Example 8.17. 8.1.7. Finding the Size of an Array PHP provides built-in functions to count the number of elements in an array. They are count(), sizeof(), and array_count_values(). Example 8.18 demonstrates how to find the size of a multidimensional array. Table 8.4. Functions to Find the Size of an Array Function What  It  Does array_count_values() Returns  an  array  consisting  of  the  values  of  an  array  and  the   number  of  times  each  value  occurs  in  an  array count() Returns  the  number  of  elements  in  an  array  or  properties  of  an   object sizeof() Returns  the  size  of  the  array,  same  as  count()   The count() and sizeof() Functions The count()[2] and sizeof() functions do the same thing: They both return the number of elements in an array (or properties in an object). To find the number of elements in a multidimensional array, the count() function has an optional mode argument that recursively counts the elements. [2] The sizeof() function is simply an alias for the count() function. Format $number_of_elments =count(array_name); $number_of_elements=count(array_name, 1); $number_of_elements=count(array_name, COUNT_RECURSIVE)   Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  20. Example: $bytes=range('a','z'); $size = count( $bytes); // 26 elements $size = sizeof( $bytes); // 26 elements Example 8.18. The count() function Explanation 1 The  array  called  $colors  is  assigned  three  values. 2 A  new  element  is  added  to  the  $colors  array. 3 The  count()  function  returns  the  number  of  elements  in  the  array. 4 See  Figure  8.22  for  the  return  from  the  count()  function. Figure 8.22. Finding the size of an array. Output from Example 8.18. The array_count_values() Function The array_count_values() function counts how many times a unique value is found in an array. It returns an associative array with the keys representing the unique element of the array, and the value containing the number of times that unique element occurred within the array. Format array array_count_values ( array input )   Example: $hash_count = array_count_values( array("a","b", "a","a")); // Creates an associative array with "a" and "b" as the two keys and // the number of times each occurs in the array (the associated value) Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
ADSENSE

CÓ THỂ BẠN MUỐN DOWNLOAD

 

Đồng bộ tài khoản
2=>2