Presentation is loading. Please wait.

Presentation is loading. Please wait.

Max(), with an array argument, returns the largest value in the array  With several numerical arguments, it returns the largest argument E.g., $arr =

Similar presentations


Presentation on theme: "Max(), with an array argument, returns the largest value in the array  With several numerical arguments, it returns the largest argument E.g., $arr ="— Presentation transcript:

1 max(), with an array argument, returns the largest value in the array  With several numerical arguments, it returns the largest argument E.g., $arr = array(5, 3, 7, 2); echo max($arr); produces 7 and echo max(7, 5, 9, 4); produces 9 min() is similar, but returns the smallest Ch. 19, Addendum 1. More PHP Arrays Inspecting Array Contents (continued)

2 array_unique( Array ) returns an array identical to Array but without duplicate values  Both the duplicate value and its key are eliminated  In the resulting array, all values are associated with the same keys they were associated with in the original array  2 values are equal if they have the same string representations E.g., $arr = array( 'Ed', 'Al', 'Sue', 'Al', 'Ed', 'Dave' ); $a_unique = array_unique( $arr ); echo print_r( $a_unique, true ); produces Array ( [0] => Ed [1] => Al [2] => Sue [5] => Dave )

3 array_count_values( Array ) returns an array with the values of Array as keys and their frequency as values E.g., $arr = array( 1, 2, 1, 3, 2, 1 ); $acv = array_count_values( $arr ); echo print_r($acv, true); produces Array ( [1] => 3 [2] => 2 [3] => 1 )

4 Sorting Arrays Compare strings by lexicographical order  Based on some underlying order of the characters  For PHP, UTF-8 encoding (agrees with ASCII on 1 st 256 characters) To determine which of 2 strings s 1 and s 2 precedes the other in lexicographical order  Compares 1 st characters of the 2 If 1 st character of s 1 precedes that of s 2, then s 1 precedes s 2 If the reverse is the case, then s 2 precedes s 1  If 1 st characters are the same, look at 2 nd characters  Etc. An initial substring of a string is taken to precede it

5 sort( Array ) sorts Array in non-descending order on the values of elements Returns true if succeeds and false if not  Like all sorting functions  We’re not usually concerned New, numeric keys are assigned to the elements  Start with 0 for smallest value By default, values are 1 st compared numerically  Only strings interpreted in their entirety as numeric are coerced to non-zero numbers E.g., ‘ cat12 ’ is coerced to 0 After all elements are sorted, elements that coerce to 0 are sorted lexicographically

6 For example, $arr = array( 'Ed', '2cats', 'mother' => 'Sue', 'gum' => 1.5, 2.5 ); sort( $arr ); echo print_r( $arr, true ); outputs Array ( [0] => 2cats [1] => Ed [2] => Sue [3] => 1.5 [4] => 2.5 )

7 Default behavior overridden by including a flag 2 nd argument:  SORT_REGULAR : compare items normally (the default)  SORT_NUMERIC : compare items numerically  SORT_STRING : compare items as strings E.g., $arr = array( 'Ed', '2cats', 'mother' => 'Sue', 'gum' => 1.5, 2.5 ); sort( $arr, SORT_NUMERIC ); echo print_r( $arr, true ); outputs Array ( [0] => Ed [1] => Sue [2] => 1.5 [3] => 2cats [4] => 2.5 )

8 Another example: $arr = array( 'Ed', '2cats', 'mother' => 'Sue', 'gum' => 1.5, 2.5 ); sort( $arr, SORT_STRING ); echo print_r( $arr, true ); outputs Array ( [0] => 1.5 [1] => 2.5 [2] => 2cats [4] => Ed [5] => Sue )

9 asort( Array ) sorts Array just like sort()  Can also modify its behavior with same 2 nd argument But, with asort(), keys retain associations with values E.g., $arr = array( 'Ed', '2cats', 'mother' => 'Sue', 'gum' => 1.5, 2.5 ); asort( $arr ); echo print_r( $arr, true ); outputs Array ( [1] => 2cats [0] => Ed [mother] => Sue [gum] => 1.5 [2] => 2.5 )

10 ksort() is like asort() but sorts on keys of elements E.g., $arr = array( 'pig' => 3, 'cows' => 2, 'horses' => 4 ); ksort( $arr ); echo print_r( $arr, true ); outputs Array ( [cows] => 2 [horses] => 4 [pig] => 3 )

11 natsort() behaves like asort() but produces a “natural” ordering:  Strings sorted as usual Except decimal integer substrings compared on their numeric values  If strings contain numeric parts (separated by non-digits), values in the respective parts are compared to break draws E.g., $arr = array( 'x3.y2', 'y2.x3', 'x20.y2', 'x3.y10' ); natsort( $arr ); echo print_r( $arr, true ); outputs Array ( [0] => x3.y2 [3] => x3.y10 [2] => x20.y2 [1] => y2.x3 )

12 One use of natsort() : sort IP addresses in a log file Case-sensitive version of natsort() is natcasesort()

13 All sorting functions covered sort in non-descending order For each but natsort(), a companion function sorting in non- ascending order: rsort(), arsort(), krsort() usort( Array ) sorts Array on its values using a user-fined comparison function uksort( Array ) sorts Array on its keys using a user-defined function Covered later, with functions

14 Other Array Functions and Operators Reordering and Randomly Accessing Array Elements array_rand( Array ) returns a randomly chosen key of Array E.g., form array $pictures of names of image files  Index into Array with a randomly chosen index Randomly chooses 1 of these names  Use the name as value of src attribute of an img element

15 <?php $pictures = array( 'carr.jpg', 'esterline.jpg', 'li.jpg' ); $pic = $pictures[ array_rand( $pictures ) ]; ?> Randomly Select a Picture The Faculty of the day is <?php echo "<img src='".$pic."' width='140' height='170'". " alt='faculty of the day'>"; ?>

16 array_rand( Array, NumKeys )  Optional 2 nd argument NumKeys specifies how many keys to choose  Defaults to 1  If NumKeys > 1, returns an array of keys

17 shuffle( Array ) randomly assigns new keys to elements of Array  Keys in sequence starting at 0  Array elements ordered in order of their keys E.g., start with same array $pictures  Shuffle it  Include images in the HTML in their order shuffled array

18 <?php $pictures = array( 'carr.jpg', 'esterline.jpg', 'li.jpg' ); shuffle( $pictures ); ?> Randomly Select a Picture Some Faculty Members <?php $size = sizeof( $pictures ); Continued

19 for ( $i=0; $i<$size; $i++ ) echo "<img src='".$pictures[$i]. "' width='140' height='170'". " alt='faculty ".($i+1)."'>\n"; ?>

20 array_reverse( Array ) returns an array with the order of the values reversed  String keys are preserved  But numeric keys are replaced Left-to-right sequence starting with 0 E.g., $father = array( 'Bob' => 'Ed', 'Sue' => 'Al', 'Ed' => 'Tim' ); $rfather = array_reverse( $father ); echo print_r( $rfather, true ); produces Array ( [Ed] => Tim [Sue] => Al [Bob] => Ed )

21 But, with numeric keys, e.g., $father = array( 'Ed', 'Al', 'Tim' ); get Array ( [0] => Tim [1] => Al [2] => Ed ) Preserve the numeric keys by including true as the optional 2 nd argument: $rfather = array_reverse( $father, true ); Then get Array ( [2] => Tim [1] => Al [0] => Ed )

22 No need for array_reverse() for array of numbers in reverse order  range() can take negative number as its optional 3 rd argument E.g., $rnums = range( 3.5, 2.0, -0.5 ); echo print_r( $rnums, true ); produces Array ( [0] => 3.5 [1] => 3 [2] => 2.5 [3] => 2 )

23 Array Operators Same equality and identity operators for arrays as for scalars  $a == $b true if arrays $a and $b contain same elements  $a === $b true if $a and $b contain same values in same order  Both != and <> are negations of ==  !== is negation of ===

24 For arrays, + is the union operator $a + $b produces a new array  Initial elements duplicate all elements of $a in same order  Elements of $b added to the end in same order they occur in $b as long as they don’t have same key as an element in $a E.g., $arr1 = array( 'a' => 1, 'b' => 2 ); $arr2 = array( 'b' => 3, 'c' => 4 ); echo print_r( $arr1 + $arr2, true ); produces Array ( [a] => 1 [b] => 2 [c] => 4 )

25 array_merge( Array 1, Array 2, Array 3, … ) is like + Returns a new array where the values of Array i+1 are appended to end of the values of Array i If 2 elements in 2 different input arrays have same string key, then the element in the earlier array is not included E.g., $arr1 = array( 'a' => 1, 'b' => 2 ); $arr2 = array( 'b' => 3, 'c' => 4 ); echo print_r( array_merge( $arr1, $arr2 ), true ); produces Array ( [a] => 1 [b] => 3 [c] => 4 )

26 But, if the arrays contain numeric keys,  all elements are merged and  result is numerically indexed starting with 0 For example, $arr1 = array( 0 => 1, 2 => 2 ); $arr2 = array( 1 => 3, 2 => 4 ); echo print_r( array_merge( $arr1, $arr2 ), true ); produces Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) So, if only 1 numerically indexed array is given, keys are re-indexed starting with 0

27 No array intersection operator, but there’s a function array_intersect( Array 1, Array 2, Array 3, … ) Returns new array with the elements of Array 1 whose values occur in all other arrays  Elements are in same order they occur in Array 1  Keys in the result are the keys of Array 1 E.g., $arr1 = array( 'a' => 1, 'b' => 2, 'c' => 3 ); $arr2 = array( 'd' => 1, 'e' => 3, 'f' => 5 ); echo print_r( array_intersect( $arr1, $arr2 ), true ); produces Array ( [a] => 1 [c] => 3 )

28 array_combine( Array 1, Array 2 ) Returns an array constructed by using  values in Array 1 as keys and  values from Array 2 as the corresponding values Correspondence is by position in the arrays Returns false if  sizeof( Array 1 )  sizeof( Array 2 ) or  arrays are empty E.g., $arr1 = array( 'milk', 'bread', 'eggs' ); $arr2 = array( 2.76, 1.85, 3.85 ); echo print_r( array_combine( $arr1, $arr2 ), true ); produces Array ( [milk] => 2.76 [bread] => 1.85 [eggs] => 3.85 )

29 Multidimensional Arrays (continued) Initialization by Assignment Besides using array() to initialize a 2D array, can use assignment to initialize  individual rows (with 1D arrays) or  individual cells within the rows PHP dynamically creates the space required To illustrate, we’ll build up the array created in the 1 st example with array(), repeated here: $scores = array( array( "Ed", 90, 85, 72 ), array( "Sue", 76, 83, 89 ), array( "Al", 86, 92, 88 ) );

30 A sequence of assignments to do this is $scores[][] = 'Ed'; $scores[0][] = 90; $scores[0][] = 85; $scores[0][] = 72; $scores[] = array( "Sue", 76, 83, 89 ); $scores[][] = 'Al'; $scores[2][] = 86; $scores[2][] = 92; $scores[2][] = 88; In practice, assignments that dynamically increase array size are in loops and at scattered locations in the code

31 The order rows are stored and the order elements are stored in a row depend on the order they’re added to the array E.g., following sequence produces rendering at right $scores[2][2] = 92; $scores[0][0] = 'Ed'; $scores[2][1] = 86; $scores[0][1] = 90; $scores[2][0] = 'Al'; $scores[0][2] = 85; $scores[0][3] = 99; $scores[2][2] = 100; echo print_r( $scores, true );

32 When initializing an array with string keys, the keys must be explicitly used  E.g., $orders = array(); $orders['Ed']['beer'] = 6; $orders['Ed']['wine'] = 4; $orders['Sue']['milk'] = 3; $orders['Sue']['bread'] = 2; $orders['Al'] = array('bread' => 1, 'beer' => 2, 'milk' => 2); produces the array on the next slide

33 Array ( [Ed] => Array ( [beer] => 6 [wine] => 4 ) [Sue] => Array ( [milk] => 3 [bread] => 2 ) [Al] => Array ( [bread] => 1 [beer] => 2 [milk] => 2 )

34 Initialization from a File Saw earlier file(Path), Path the pathname of a file  Reads this file and return an array of its lines In the previous example: $orders = file( "$DOCUMENT_ROOT/../phpData/orders.txt" ); $number_of_orders = sizeof( $orders ); for ( $i=0; $i<$number_of_orders; $i++ ) echo "{$orders[$i]} "; But usually want to extract various values from an input line  Straightforward extension is a 2D array

35 Example orders file: Al17:49, 21st October1 quarts of milk6 bottles of beer$20.08 Ed17:50, 21st October6 quarts of milk1 bottles of beer$24.20 Fred12:01, 22nd October3 quarts of milk2 bottles of beer$16.23 Bill12:05, 22nd October1 quarts of milk12 bottles of beer$36.58 The output of the script for this orders file:

36 Use explode() to return an array of the tab-delimited substrings of a line explode( Str 1, Str 2 ) returns an array of substrings of Str 2 delimited by Str 1  If no occurrence of Str 1 in Str 2, returns an array whose sole value is Str 2 E.g., $arr = explode( '/', '11/16/2007' ); echo print_r( $arr, true ); outputs Array ( [0] => 11 [1] => 16 [2] => 2007 )

37 Using list() with explode(), assign parts of interest to scalar variables  Use placeholders to ignore other pieces E.g., list( $month,, $year ) = explode( '/', '11/16/2007' ); sets $month to ‘ 11 ’ and $year to ‘ 2007 ’

38 Optional 3 rd argument specifies (when positive) max number of elements returned  If limit reached, last part of Str 2 isn’t split E.g., $arr = explode( '/', '11/16/2007', 2 ); echo print_r( $arr, true ); outputs Array ( [0] => 11 [1] => 16/2007 ) If 3 rd argument negative, specifies number of substrings ignored at the end E.g., $arr = explode( '/', '11/16/2007', -1 ); echo print_r( $arr, true ); outputs Array ( [0] => 11 [1] => 16 )

39 implode( Str, Array ), Array an array of substrings  Returns the string formed by connecting together the substrings with Str E.g., $str = implode( '/', array( '11', '16', '2007' ) ); sets $str to ‘ 11/16/2007 ’

40 Back to the script in question Read orders file into array $order_lines and record number of lines: $order_lines = file( "$DOCUMENT_ROOT/../phpData/orders.txt" ); $number_of_lines = sizeof( $order_lines ); Loop over the lines, setting row $i of 2D array $orders to contain  client’s name (in $orders[$i][0] )  number of quarts of milk ordered (in $orders[$i][1] )  number of bottles of beer ordered (in $orders[$i][2] )

41 list( $orders[$i][0],, $milkqty, $beerqty ) = explode( "\t", $order_lines[$i] );  Need double-quotes around \t String in $milkqty has non-digits after the digits characters  Get the number off the front with intval($milkqty) Assign this to $orders[$i][1] and use its value to increment running total $milk_tot += $orders[$i][1] = intval( $milkqty ); Likewise for number of bottles of beer $beer_tot += $orders[$i][2] = intval( $beerqty ); Note: $milkqty and $beerqty needn’t be initialized to 0 ( NULL coerces to 0)

42 Entire loop for initializing array and variables for totals: for ( $i=0; $i<$number_of_lines; $i++ ) { list( $orders[$i][0],, $milkqty, $beerqty ) = explode( "\t", $order_lines[$i] ); $milk_tot += $orders[$i][1] = intval( $milkqty ); $beer_tot += $orders[$i][2] = intval( $beerqty ); }

43 In HTML body, check if no orders placed  If so, tell the user and exit, outputting closing tags: if ( $number_of_lines == 0 ) exit( " No pending orders " ); To output the orders in the table rows: for ( $i=0; $i<$number_of_lines; $i++ ) { echo " "; for ( $j=0; $j<3; $j++ ) echo " {$orders[$i][$j]} "; echo " "; } To output the last row, with totals : echo " Total $milk_tot ". " $beer_tot \n";

44 The entire script: <?php $DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT']; $order_lines = file( "$DOCUMENT_ROOT/../phpData/orders.txt" ); $number_of_lines = sizeof( $order_lines ); for ( $i=0; $i<$number_of_lines; $i++ ) { list( $orders[$i][0],, $milkqty, $beerqty ) = explode( "\t", $order_lines[$i] ); $milk_tot += $orders[$i][1] = intval( $milkqty ); $beer_tot += $orders[$i][2] = intval( $beerqty ); } ?> Continued

45 Al's Grocery - Customer Orders <?php if ( $number_of_lines == 0 ) exit( " No pending orders \n \n " ); ?> Al's Grocery - Customer Orders Milk Beer Continued

46 <?php echo "\n"; for ( $i=0; $i<$number_of_lines; $i++ ) { echo " "; for ( $j=0; $j<3; $j++ ) echo " {$orders[$i][$j]} "; echo " \n"; } echo " Total $milk_tot ". " $beer_tot \n"; ?>

47 Initialization from Form Data Earlier: Value of name attribute of form elements supplying array data indicate an array by ending with “ [] ” Had several checkboxes all with name “ student[] ”, e.g., <input type="checkbox" name="student[]" value="Sue"> PHP script fielding the submission copied the array that’s the value of form variable student into $student : $student = $_GET['student'];  Contains value of each checked checkbox whose name is ‘ student[] ’

48 Can send 2D arrays as form data by using obvious extensions E.g., in HTML document rendered at right, form elements are checked or filled in Students are now divided into 2 groups: girls and boys  Some have name “ student[girls][] ”  Others have name “ student[boys][] ” With form filled in as shown, array sent is what would be created with array( 'girls' => array('Sue', 'Pam' ), 'boys' => array('Ed' ) )

49 Also a table with 8 text boxes, 2 for each student  One for student’s score on exam 1  Other for his score on exam 2 Their values are recorded in 2D array scores  1 st key is student’s name  2 nd is 0 (for exam 1) or 1 (for exam 2) E.g., for Sue, With text boxes filled as shown, array sent is what would be created with array( 'Sue' => array( 78, 81 ), 'Ed' => array( 56, 52), 'Al' => array( 89, 95 ), ' Pam' => array( 82, 74 ))

50 PHP script fielding this form’s submission echoes array values For our example, HTML produced is rendered as shown Written so that it would produce intended results if  more groups added to student array or  more individuals added to each group Would also produce intended table if  more names added to the scores array or  more exams recorded. Advantages of arrays with forms analogous to advantages of arrays (rather than scalar variables) in programs in general

51 Listing of the HTML document 2D Arrays Check the students who attended <input type="checkbox" name="student[girls][]" value="Sue"> Sue <input type="checkbox" name="student[boys][]" value="Ed"> Ed Continued

52 <input type="checkbox" name="student[boys][]" value="Al"> Al <input type="checkbox" name="student[girls][]" value="Pam"> Pam Enter the grades for the exams Exam 1 Exam 2 Continued

53 Sue <input type='text' name='scores[Sue][0]' size='4'> <input type='text' name='scores[Sue][1]' size='4'> Ed <input type='text' name='scores[Ed][0]' size='4'> <input type='text' name='scores[Ed][1]' size='4'> Continued

54 Al <input type='text' name='scores[Al][0]' size='4'> <input type='text' name='scores[Al][1]' size='4'> Pam <input type='text' name='scores[Pam][0]' size='4'> <input type='text' name='scores[Pam][1]' size='4'>

55 Script copies array values of the form variables student and scores into corresponding program variables: $student = $_GET['student']; $scores = $_GET['scores']; In the body of the HTML, loop over rows of $student array  $group gets value of successive keys  $st assigned corresponding arrays of names $group output on each iteration Inner loop iterates over (and outputs) names in $st

56 The loop is foreach ( $student as $group => $st ) { echo "The following were present among ". "the $group: "; foreach ( $st as $s ) echo "$s "; echo " "; } Note  Any number of groups (with any names) can be handled  Number of names in any group is unconstrained  Groups generally have different numbers of members

57 Nested loop producing rows in the table after the 1 st row (with column headings): foreach ( $scores as $name => $scrs ) { echo " $name "; foreach ( $scrs as $scr ) echo " $scr "; echo " \n"; } Listing of entire PHP script follows

58 <?php $student = $_GET['student']; $scores = $_GET['scores']; ?> 2D Arrays Continued

59 <?php echo "\n"; foreach ( $student as $group => $st ) { echo " The following were present among the ". "$group: \n "; foreach ( $st as $s ) echo "$s "; echo " \n"; } ?> Continued

60 Exam Scores Exam 1 Exam 2 <?php echo "\n"; foreach ( $scores as $name => $scrs ) { echo " $name "; foreach ( $scrs as $scr ) echo " $scr "; echo " \n"; } ?>


Download ppt "Max(), with an array argument, returns the largest value in the array  With several numerical arguments, it returns the largest argument E.g., $arr ="

Similar presentations


Ads by Google