1 chapter 3 – handling strings and arrays spring into php 5 by steven holzner slides were...

25
1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology Radford University

Upload: dennis-stone

Post on 19-Jan-2016

223 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

1

Chapter 3 – Handling Strings and Arrays

spring into PHP 5by Steven Holzner

Slides were developed by Jack Davis

College of Information Scienceand Technology

Radford University

Page 2: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

2

String Functions

• Lots of string functions are built into PHP. There are string functions that sort, search, trim, change case, and more in PHP. We’ll look at many of these but not all. Most of the important string functions are listed on pp 66-67 in the text.

• trim, ltrim, rtrimThese functions trim whitespace characters, usually blanks, from either or both ends of a string variableecho trim(" No worries. ", "\n");--No worries.

• print, echoDisplays a string.print ("abc \n"); print "var = $var";echo "abc", "\n"; note - inside double quotes, variables are interpolated (they are replaced by their value

• strlenreturns the length of a string$len = strlen("abcd"); (($len will be 4))

Page 3: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

3

String Functions (cont.)

• strposfinds position of the first occurrence of a target string inside a source string$pos = strpos("ITEC 325","32");--- $pos will have value 5

• strrevreverses the characters in a string$str = "abcd";$newstr = strrev($str);--- $newstr will have value "dcba"

• substrreturns a portion of a string- first index is the start of the substring- second index is the length of the substringecho substr("ITEC 325", 5, 3);

• substr_replacereplace a target portion of a string with a new substringecho substr_replace("no way", "yes", 0,2);-- what will be displayed?

Page 4: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

4

String Functions (cont.)

• strtolower, strtoupperchanges string to all lower or upper case characters$lowcas = strtolower("ABCdef");-- $lowcas will have value "abcdef"

• strncmpbinary safe comparison of two strings for a given number of characters, returns -1, 0, or 1$ind = strncmp("ABC", "DEF", 3);

• strnatcmpperforms natural comparison of two stringsreturns -1, 0, 1$ind = strnatcmp("ABC", "def");

• we'll look at some more string functions that work with arrays.

• there are many, many more string functions, see table B-3 in your text

Page 5: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

5

Formatting Strings

• There are two string functions that are very useful when you want to format data for display, printf and sprintf.

printf (format [, args])sprintf (format [,args])

The format string is composed of zero or more directives: characters that are copied directly to the result, and conversion specifications. Each conversion specification consists of a percent sign (%), followed by one or more of these elements, in order:- optional padding specifier indicating what character should be used to pad the results to the correct string size, space or a 0 character.- optional alignment specifier indicating whether the results should be left or right justified.- optional number, width specifier, specifying how many minimum characters this conversion should result in

Page 6: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

6

Formatting Strings (cont.)

- optional precision specifier that indicates how many decimal digits should be displayed for floating point numbers.- a type specifier that says what type argument the data should be treated as

Possible type specifiers are:- percent character, no argument required- integer presented as binary- integer presented as the character with that ASCII value- integer presented as a signed decimal- integer presented as unsigned decimal- float presented as a float- integer presented as octal- string string- integer presented as hex lowercase- integer presented as hex uppercase

Page 7: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

7

Formatting Strings (cont.)

• printf ("I have %s apples and %s oranges. \n", 4, 56);

output is:I have 4 apples and 56 oranges.

• $year = 2005; $month = 4; $day = 28;printf("%04d-%2d-%02d\n", $year, $month, $day);

output is:2005-04-28

• $price = 5999.99;printf("\$%01.2f\n", $price);

output is:$5999.99

Page 8: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

8

Formatting Strings (cont.)

• printf("%6.2f\n", 1.2);printf("%6.2f\n", 10.2);printf("%6.2f\n", 100.2);

output is:

1.20 10.20100.20

• $string = sprintf("Now I have %s apples and %s oranges.\n", 3, 5);echo $string;

output is:Now I have 3 apples and 5 oranges.

Page 9: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

9

Converting to & from Strings.

• Converting between string format and other formats is a common task in web programming.

To convert a float to a string:$float = 1.2345;echo (string) $float, "\n";echo strval($float), "\n";

• A boolean TRUE is converted to the string "1" and FALSE to an empty string "". An int or float is converted to a string with its digits and decimal points. The value NULL is always converted to an empty string. A string can be converted to a number, it will be a float if it contains '.', 'e', or 'E'. PHP determines the numeric value of a string from the initial part of the string. If the string starts with numeric data, it will use that. Otherwise, the value will be 0.

Page 10: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

10

Converting to & from Strings (cont)

• Examples:

$number = 1 + "14.5";echo "$number\n";-- will output 15.5

$number = 1 + "-1.5e2";echo "$number\n";-- will output -149

$text = "5.0";$number = (float) $text;echo $number / 2.0, "\n";-- will output 2.5

$a = 14 + "dave14";echo $a, "\n";-- will output

$a = "14dave" + 5;echo $a, "\n";-- will output

Page 11: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

11

Creating Arrays

• Arrays are easy to handle in PHP because each data item, or element, can be accessed with an index value. Arrays can be created when you assign data to them, array names start with a $.

$students[1] = "John Smith";

this assignment statement creates an array named $students and sets the element at index 1 to "John Smith"

echo $students[1];

to add elements:$students[2] = "Mary White";$students[3] = "Juan Valdez";

you can also use strings as indexes:$course["web_programming"] = 325;$course["java_1"] = 120;((sometimes called associative arrays))

Page 12: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

12

Creating Arrays (cont.)

• shortcut for creating arrays

$students[] = "John Smith";$students[] = "Mary White";$students[] = "Juan Valdez";

in this case $students[0] will hold "John Smith" and $students[1] will hold "Mary White", etc.

you can also create an array -- $students = array("John", "Mary", "Juan");

or like the above but specify indexes

$students = array (1 =>"John", 2=>"Mary", 3=>"Juan");or --$courses = array("web"=>325, "java1" => 120);

the => operator lets you specify key/value pairs

Page 13: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

13

Modifying Array Values

• current array values$students[1] = "John Smith";$students[2] = "Mary White";$students[3] = "Juan Valdez";

$students[2] = "Kathy Jordan"; //modify

$students[4] = "Michael Xu"; // add new

$students[] = "George Lau"; // add new [5]

• looping through an array

for ($ct=1; ct<count($students); $ct++) { echo $students[ct], "<br />", "\n"); }

• test what value the function count returns when we have a sparse array!

Page 14: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

14

Modifying Arrays (cont.)

• consider:$student[0] = "Mary"; // what's the prob???$students[1] = "John";$students[2] = "Ralph";

$students[0] = "";this sets the element to null, but does not remove the element from the array

to remove an element use the unset function

unset($students[0]);

without looping you can also display the contents of an array with print_r(print array)

print_r($students); Array{ [1] => John [2] => Ralph }

Page 15: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

15

foreach loop with Arrays

• useful to access all the elements of the array without having to know what the indices are, it has two forms:

foreach (array as $value) { statement(s) }

foreach (array as $key => $value) { statement(s) }

in the first, $value takes on each value in the array in succession.

in the second form $key takes on the index and $value takes the value of the array, careful it's easy to confuse the two.

Page 16: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

16

Arrays & loops

• $students = array("White" => junior, "Jones" => senior, "Smith" => soph);

foreach ($students as $key => $val) { echo "Key: $key Value: $val\n<br />"; }

• can also use the each function in a while loop

while (list($key, $val) = each ($students)) { echo "Key: $key; Value: $val\n<br />"; }

Page 17: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

17

Sorting Arrays

• $fruits[0] = "tangerine";$fruits[1] = "apple";$fruits[2] = "orange";

sort($fruits);

now $fruits[0] = "apple", etc.

rsort($fruits);

now $fruits[0] = "tangerine";

$fruits["good"] = "apple";$fruits["better"] = "orange";$fruits["best"] = "banana";

asort($fruits) results in apple, banana, orangeNote - sorted by value, but keys are maintained

ksort($fruits) results in banana, orange, applesorts based on the indexes

Page 18: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

18

Navigating through Arrays

• PHP includes several functions for navigating through arrays

consider an array has a pointer to the "current" element, this could be any element in the array

set the current pointer to the first element in the array

reset($students);

echo current($students);

set the current pointer to the next or previous element

next($students); prev($students);

echo next($students);

Page 19: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

19

Implode and Explode

• convert between strings and arrays by using the PHP implode and explode functions

$cars = array("Honda", "Ford", "Buick");$text = implode(",", $cars);$text contains: Honda,Ford,Buick

• $cars = explode(",",$text);

now $cars -- ("Honda", "Ford", "Buick");

• use the list function to get data values from an array

list ($first, $second) = $cars;

$first will contain "Honda"$second will contain "Ford"

-- can also use the extract function

Page 20: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

20

Merging & Splitting Arrays

• $students[] = "Mary";$students[] = "Ralph";$students[] = "Karen";$students[] = "Robert";

you can slice off part of an array:

$substudents = array_slice($students,1,2);1 -- the array element you want to start (offset)2 - the number of elements (length)$substudents now contains?

if the offset is negative, the sequence will be measured from the end of the array. if the length is negative, the sequence will stop that many elements from the end of the array.

$newstudents = array("Frank", "Sheila");

merge the two arrays:$mergestudents = array_merge($students, $newstudents);

Page 21: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

21

Comparing Arrays

• PHP includes functions that will determine which elements are the same in two arrays and which are different.

$local_fruits = array("apple", "peach", "orange");

$tropical_fruits = array("banana", "orange", "pineapple");

$diff = array_diff($local_fruits, $tropical_fruits);(values in 1st array, not in second array)$diff will contain -- apple, peach

$common = array_intersect($local_fruits, $tropical_fruits);

$common will contain -- orange

can also work with associative arrays with array_diff_assoc or array_intersect_assoc

Page 22: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

22

Array Functions

• delete duplicate elements in an array

$scores = array(65, 60, 70, 65, 65);$scores = array_unique($scores);now scores has (65, 60, 70)

• sum elements of an array

$sum = array_sum($scores);now $sum has value 195

• the array_flip function will exchange an array's keys and values

Page 23: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

23

Multidimensional Arrays

• $testscor['smith'][1] = 75;$testscor['smith'][2] = 80;$testscor['jones'][1] = 95;$testscor['jones'][2] = 85;

have two indexes, so a two dimensional array

can use nested for loops to access and process all the elements

foreach ($testscor as $outerkey => $singarr) { foreach($singarr as $innerkey => $val) { statements, average each students test scores… } }

• Multidimensional sort - listing• Multidimensional sort - execute

Page 24: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

24

Multi-dimensional array sort

• <html>• <!-- mularraysort.php• example of sorting a multidimensional array -->• <head> <title>multi-dimensional array sort</title> </head>• <body>• <h2>Multi-dimensional array sort.</h2>• <p>• <?php • // set array elements• $testscor['smith'][1] = 71; $testscor['smith'][2] = 80;• $testscor['smith'][3] = 78; $testscor['jones'][1] = 91;• $testscor['jones'][2] = 92; $testscor['jones'][3] = 93;

• // print array elements• foreach ($testscor as $nkey => $scorarr)• {• $tot = 0; $noscor = 0;• echo "test scores for $nkey<br>\n";• foreach($scorarr as $testkey => $val)• {• $tot = $tot + $val;• $noscor ++;• echo "$testkey - $val<br>\n";• }• $avg = $tot / $noscor;• printf ("test average = %02.2f<br>\n",$avg);• }• ?>• </p> <p>• <?php• // let's sort the $testscor array for each name • foreach ($testscor as $nkey => $narray)• {• sort($testscor[$nkey]);• }

Page 25: 1 Chapter 3 – Handling Strings and Arrays spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology

25

Array Operators

• consider $aar and $bar are both arrays

$aar + $bar union

$aar == $bar TRUE, if have all same elements

$aar === $bar TRUE, if same elements in same order

$aar != $bar TRUE, not same elements

$aar <> $bar same as above

$aar !== $bar TRUE, not same elements in same order