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.

Slides:



Advertisements
Similar presentations
Container Types in Python
Advertisements

CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
C Characters & Strings Character Review Character Handling Library Initialization String Conversion Functions String Handling Library Standard Input/Output.
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Characters and Strings.
Java Programming Strings Chapter 7.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Chapter 8 Characters and Strings Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Differences between Java and C CS-2303, C-Term Differences between Java and C CS-2303, System Programming Concepts (Slides include materials from.
Display a 12-Month Calendar CS-2301 D-term Programming Assignment #2 12-Month Calendar CS-2301 System Programming C-term 2009 (Slides include materials.
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
More on Numerical Computation CS-2301 B-term More on Numerical Computation CS-2301, System Programming for Non-majors (Slides include materials from.
Introduction to Oracle9i: SQL1 Selected Single-Row Functions.
Chapter 8 Arrays and Strings
Assignment #2, 12- month Calendar CS-2301, B-Term Programming Assignment #2 12-Month Calendar CS-2301, System Programming for Non-Majors (Slides.
The printf Method The printf method is another way to format output. It is based on the printf function of the C language. System.out.printf(,,,..., );
August Chapter 1 - Essential PHP spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology.
Strings and Arrays. String Is a sequence of characters. Example: “hello”, “how are you?”, “123”,and are all valid string values.
Strings PART II STRING$ AND SPACE$. Create strings of specified number String$ creates string of specified character Space$ creates string of spaces Example:
Strings IDIA 618 Spring 2013 Bridget M. Blodgett.
Lists in Python.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
Chapter 10 Selected Single-Row Functions Oracle 10g: SQL.
Chapter 5 Selected Single-Row Functions. Chapter Objectives  Use the UPPER, LOWER, and INITCAP functions to change the case of field values and character.
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
PHP Strings. Outline o String Variables In PHP o The Most Used Functions In PHP o Arrays Functions o Transforming String o Comparing Strings o Searching.
Web Database Programming Week 3 PHP (2). Functions Group related statements together to serve “a” specific purpose –Avoid duplicated code –Easy maintenance.
Oracle 11g: SQL Chapter 10 Selected Single-Row Functions.
An Introduction to Java Programming and Object-Oriented Application Development Chapter 7 Characters, Strings, and Formatting.
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
Manipulating Strings. What is a string? Data composed of text characters. The data is stored in consecutive bytes of memory. Each byte stores the ASCII.
Chapter 9: Perl Programming Practical Extraction and Report Language Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Basic Data Types Numbers (integer and floating point)‏ Strings (sequences of characters)‏ Boolean values (true/false)‏
Operations on Strings. 8/8/2005 Copyright 2006, by the authors of these slides, and Ateneo de Manila University. All rights reserved L: String Manipulation.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Chapter 5 Strings CSC1310 Fall Strings Stringordered storesrepresents String is an ordered collection of characters that stores and represents text-based.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI C-Style Strings Strings and String Functions Dale Roberts, Lecturer.
More Strings CS303E: Elements of Computers and Programming.
ICT Introduction to Programming Chapter 4 – Control Structures I.
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Input and Output.
UniMAP SEM I - 09/10EKT 120 Computer Programming1 Lecture 8 – Arrays (2) & Strings.
Chapter 8 Characters and Strings. Objectives In this chapter, you will learn: –To be able to use the functions of the character handling library ( ctype).
 Variables can store data of different types, and different data types can do different things.  PHP supports the following data types:  String  Integer.
8 1 String Manipulation CGI/Perl Programming By Diane Zak.
Strings PART I STRINGS, DATES, AND TIMES. FUNDAMENTALS OF CHARATERS AND STRINGS VB represents characters using American National Standards Institute(ANSI)
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
Variable Variables A variable variable has as its value the name of another variable without $ prefix E.g., if we have $addr, might have a statement $tmp.
Creating PHP Pages Chapter 10 PHP Arrays. Arrays An array can store one or more values in a single variable name. An element of an associative accessed.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
CSC 162 Visual Basic I Programming. String Functions LTrim( string ) –Removes leading spaces from the left side of string RTrim( string ) –Removes trailing.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
String and Lists Dr. José M. Reyes Álamo.
Do-more Technical Training
Chapter 10 Selected Single-Row Functions Oracle 10g: SQL
Strings Part 1 Taken from notes by Dr. Neil Moore
Formatting Output.
PHP.
String and Lists Dr. José M. Reyes Álamo.
Differences between Java and C
String functions
Fundamentals of Python: First Programs
CS2011 Introduction to Programming I Strings
Introduction to Computer Science
String functions
Presentation transcript:

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

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 in the text. trim, ltrim, rtrim These functions trim whitespace characters, usually blanks, from either or both ends of a string variable echo trim(" No worries. ", "\n"); --No worries. print, echo Displays a string. print ("abc \n"); print "var = $var"; echo "abc", "\n"; note - inside double quotes, variables are interpolated (they are replaced by their value strlen returns the length of a string $len = strlen("abcd"); (($len will be 4))

3 String Functions (cont.) strpos finds position of the first occurrence of a target string inside a source string $pos = strpos("ITEC 325","32"); --- $pos will have value 5 strrev reverses the characters in a string $str = "abcd"; $newstr = strrev($str); --- $newstr will have value "dcba" substr returns a portion of a string - first index is the start of the substring - second index is the length of the substring echo substr("ITEC 325", 5, 3); substr_replace replace a target portion of a string with a new substring echo substr_replace("no way", "yes", 0,2); -- what will be displayed?

4 String Functions (cont.) strtolower, strtoupper changes string to all lower or upper case characters $lowcas = strtolower("ABCdef"); -- $lowcas will have value "abcdef" strncmp binary safe comparison of two strings for a given number of characters, returns -1, 0, or 1 $ind = strncmp("ABC", "DEF", 3); strnatcmp performs natural comparison of two strings returns -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

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

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

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: $price = ; printf("\$%01.2f\n", $price); output is: $

8 Formatting Strings (cont.) printf("%6.2f\n", 1.2); printf("%6.2f\n", 10.2); printf("%6.2f\n", 100.2); output is: $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.

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 = ; 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.

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

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))

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

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 ", "\n"); } test what value the function count returns when we have a sparse array!

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 }

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.

16 Arrays & loops $students = array("White" => junior, "Jones" => senior, "Smith" => soph); foreach ($students as $key => $val) { echo "Key: $key Value: $val\n "; } can also use the each function in a while loop while (list($key, $val) = each ($students)) { echo "Key: $key; Value: $val\n "; }

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, orange Note - sorted by value, but keys are maintained ksort($fruits) results in banana, orange, apple sorts based on the indexes

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);

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

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);

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 1 st 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

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

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

24 Multi-dimensional array sort <!-- mularraysort.php example of sorting a multidimensional array --> multi-dimensional array sort Multi-dimensional array sort. <?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 \n"; foreach($scorarr as $testkey => $val) { $tot = $tot + $val; $noscor ++; echo "$testkey - $val \n"; } $avg = $tot / $noscor; printf ("test average = %02.2f \n",$avg); } ?> <?php // let's sort the $testscor array for each name foreach ($testscor as $nkey => $narray) { sort($testscor[$nkey]); }

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