520 likes | 536 Views
Learn about arrays in PHP, including the different types of arrays, how to construct and manipulate them, and useful array functions. Practice exercises included.
E N D
Overview • Arrays • Flow Control – foreach • Functions of Strings • Object Oriented • Exception Handling
Arrays (1) • Something like cabinets. • You can put something in it. • You can leave some empty space in. • Two types: • Indexed Arrays • Index # Value • Associative Arrays • Key Value ※ These two types can be mix-used,but No duplicate index numbers or keys are allowed!
Index $ary[] Element of $ary[]with index=5 Arrays (2) • Indexed Arrays • Index # Value • The default start number of index is zero. • Ex. • To indicate one elements in array: $ary_name[idx_num] • Ex. $ary[3]
$scores[] = 80; $scores[] = 65; $scores[] = 89; $scores[] = 93; = Arrays (3) • Construction • Need no declaration. • Two methods: • Using 「array()」. • Assign values directly. • Array • ( • [0] => 80 • [1] => 65 • [2] => 89 • [3] => 93 • ) $scores = array (80, 65, 89, 93); echo $scores[0]; // output 80 echo $scores[1]; // output 65 echo $scores[2]; // output 89 echo $scores[3]; // output 93 print_r ($scores); $scores[0] = 80; $scores[1] = 65; $scores[2] = 89; $scores[3] = 93; print_r ($scores); • print_r: • Prints human-readable information about a variable
Key $ary[] Element of $ary[]with key=Alice Arrays (4) • Associative Arrays • Key Value • Ex. • To indicate one elements in array: $ary_name[key] • Ex. $ary[‘John’]
Arrays (5) • Construction • Need no declaration. • Two methods: • Using 「array( Key=>Value)」. • Assign Key & Value directly. • Array • ( • [Bob] => 80 • [John] => 65 • [Mary] => 89 • [Andy] => 93 • ) $scores = array('Bob'=>80, 'John'=>65, 'Mary'=>89, 'Andy'=>93 ); print_r ($scores); $scores['Bob'] = 80; $scores['John'] = 65; $scores['Mary'] = 89; $scores['Andy'] = 93; print_r ($scores);
Arrays (6) • Accessing arrays • Reading $ary_name[ idx_num or key] $scores = array (80, 65, 89, 'Andy'=>93); $c = $scores[2]; $d = $scores['Andy']; echo $c; // output 89 echo $d; // output 93 echo $scores[1]; // output 65 echo $scores['Andy']; // output 93
Arrays (7) • Adding/Modifying $ary_name[ idx_num or key] = expression; • To change the index value while adding. $scores = array (80, 65, 89, 'Andy'=>93); $scores[1] = 70; $scores['Andy'] = 95; $scores[3] = 86; echo $scores[1]; // output 70 echo $scores['Andy']; // output 95 echo $scores[3]; // 86 print_r($scores); • Array • ( • [0] => 80 • [1] => 70 • [2] => 89 • [Andy] => 95 • [3] => 86 • ) • Array • ( • [0] => 80 • [1] => 70 • [6] => 89 • [7] => 93 • [8] => 88 • ) $scores = array (80, 65, 6=>89, 93); $scores[] = 88; print_r($scores);
Arrays (8) • Deleting unset ( $ary_name[ idx_num or key] ); • Array • ( • [0] => 80 • [2] => 89 • ) $scores = array (80, 65, 89, 'Andy'=>93); unset ( $scores[1] ); unset ( $scores['Andy'] ); print_r($scores); • Array • ( • [0] => 80 • [1] => 65 • [3] => 93 • [2] => 76 • ) $scores = array (80, 65, 89, 93); unset ( $scores[2] ); $scores[2] = 76; print_r($scores);
Arrays (9) Array ( [0] => Charlie [1] => John [2] => David ) • Practicing • 1. Print the List Array • 2. Print the Associate Array • 3. Add Jaina to the Associate Array like • 4. Edit John’s Score to 40 and Delete David’s Data. http://tphp.cs.nctu.edu.tw/tphp/pr3-1_1.php http://tphp.cs.nctu.edu.tw/tphp/pr3-1_1.txt Array ( [Charlie] => 84 [John] => 47 [David] => 29 ) http://tphp.cs.nctu.edu.tw/tphp/pr3-1_2.php http://tphp.cs.nctu.edu.tw/tphp/pr3-1_2.txt Array ( [Charlie] => 84 [John] => 47 [David] => 29 [Jaina] => 77 ) http://tphp.cs.nctu.edu.tw/tphp/pr3-1_3.php http://tphp.cs.nctu.edu.tw/tphp/pr3-1_3.txt Array ( [Charlie] => 84 [John] => 40 [Jaina] => 77 ) http://tphp.cs.nctu.edu.tw/tphp/pr3-1_4.php http://tphp.cs.nctu.edu.tw/tphp/pr3-1_4.txt
Not This Arrays (10) • 2-Dimentional Array • Something likes matrix. • One array, each elementin it is also array. • Notation $ary_name[key1][key2] • Example $name_score[“David”][“score”] = “77”;
Arrays (11) • Array Operators
Arrays (12) Array( [a] => apple [b] => banana [c] => cherry ) Array( [a] => pear [b] => strawberry [c] => cherry ) • Examples $a = array("a" => "apple", "b" => "banana"); $b = array("a" => "pear", "b" => "strawberry", "c" => "cherry"); print_r ( $a + $b ); // Union of $a and $b print_r ( $b + $a ); // Union of $b and $a Array( [x] => 70 [y] => 80 ) Array( [y] => 80 [x] => 70 ) $a = array( "x"=>70, "y"=>80); $b = array( "y"=>80, "x"=>70); print_r($a); print_r($b); echo ($a==$b) ? "equal" :"not equal"; // output equal echo ($a===$b)? "identical" : "not identical"; // output not indentical $a = array( 70, 80); $b = array( 70, "80"); echo ($a==$b) ? "equal" :"not equal"; // output equal echo ($a===$b)? "identical" : "not identical"; // output not identical
Arrays (13) • Functions for Arrays [Ref] http://www.php.net/manual/en/ref.array.php • Getting Properties • count(array) – getting array size (# of elements) • Accessing • array_pad(array) – Pad array to the specified length with a value. • array_unique(array) – Returns a new array without duplicate values. • array_reverse(array) – Return an array with elements in reverse order. • array_keys(array) – Return all the keys of an array. • array_values(array) – Return all the values of an array.
Arrays (14) • Using Array’s Internal Pointer • reset, next, prev, end • Moving Internal Pointer • current, key • Get value/key of the record pointed by I.P. • list(var1, var2, …) – Assign variables as if they were an array. $box = array ( 200, 80, 70); list ($x, $y, $z) = $box; //$x=200, $y=80, $z=70 • each(array) • Return the current key and value pair from an array, advance the array cursor. 0 = 60 1 = 50 2 = 40 $a = array ( 60, 50, 40); while (list ($k, $v) = each($a)) echo "$k = $v";
Array([0] => apple[1] => banana[2] => lemon[3] => orange) Array([c] => apple[b] => banana[d] => lemon[a] => orange) Array([a] => orange[b] => banana[c] => apple[d] => lemon) Arrays (15) • Sorting In Arrays • sort, rsort • Sort an array • asort, arsort • Sort an array and maintain index association • ksort, krsort • Sort an array by key. (will also keep index association) • Example echo "<br />\n"; $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"); $s = $fruits; sort($s); $a = $fruits; asort($a); $k = $fruits; ksort($k); print_r($s); print_r($a); print_r($k);
Arrays (16) • Searching In Arrays • in_array($value, $array, [$bool]) • Return TRUE if value exists in array. • array_search ($value, $array, [$bool]) • Return index/key. • Example $os = array("Mac", "NT", "Irix", "Linux");if (in_array("Irix", $os)) echo "Got Irix";if (in_array("mac", $os)) echo "Got mac"; Got Irix $array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');$key = array_search('green', $array); // $key = 2;$key = array_search(‘yellow', $array); // $key = false;
74 78 25 75 95 58 12 11 46 93 0 60 38 35 100 6 96 10 24 25 65 57 60 23 42 77 3 29 95 50 Arrays (17) • Practicing • 1. Sort the score list and Print it (from high to low). • 2. Find if 77, 32 are in the list. http://tphp.cs.nctu.edu.tw/tphp/pr3-2_1.php http://tphp.cs.nctu.edu.tw/tphp/pr3-2_1.txt http://tphp.cs.nctu.edu.tw/tphp/pr3-2_2.php http://tphp.cs.nctu.edu.tw/tphp/pr3-2_2.txt
Flow Control – foreach (1) • How to get every keys & values in an array? • “print_r” only print it out, not accessible. • How about this? • Only suitable for indexed arrays, andnot allowing “holes” in arrays. • Better one • But too complex for ( $i = 0; $ary[$i] != NULL; $i++){ … // $i is index, $ary[$i] is value } reset($ary); while (($v=current($ary))!=NULL){ $k = key($ary); … // $k is key, $v is value next($ary); }
Flow Control – foreach (2) • Rewrite to “for loop” • Seems better, but… I don’t like it. • Using foreach • Syntax: foreach ($array as $key => $value) { … } foreach ($array as $value) { // when $key not needed … } for(reset($ary);$v=current($ary);next($ary)){ $k = key($ary); … // $k is key, $v is value } foreach ($ary as $k => $v){ … // $k is key, $v is value }
Flow Control – foreach (3) • Another approach – using list & each • Syntax: reset($array); while ( list($key, $value)=each($array)) { … } reset($array); while ( list(, $value)=each($array)) { // when $key not needed … } reset($ary); while (list($k, $v)=each($ary)) { … // $k is key, $v is value }
Flow Control – foreach (4) • Practicing • 1. Use foreach to dump the score list. • 2. Use while to dump the score list. • 3. Use foreach to dump the score list twice. • 4. Use while to dump the score list twice. Array ( [Charlie] => 84 [John] => 47 [David] => 29 [Jaina] => 77 ) http://tphp.cs.nctu.edu.tw/tphp/pr3-3_1.php http://tphp.cs.nctu.edu.tw/tphp/pr3-3_1.txt http://tphp.cs.nctu.edu.tw/tphp/pr3-3_2.php http://tphp.cs.nctu.edu.tw/tphp/pr3-3_2.txt http://tphp.cs.nctu.edu.tw/tphp/pr3-3_3.php http://tphp.cs.nctu.edu.tw/tphp/pr3-3_3.txt http://tphp.cs.nctu.edu.tw/tphp/pr3-3_4.php http://tphp.cs.nctu.edu.tw/tphp/pr3-3_4.txt
Functions of Strings (1) • Strings – Characters connected, quoted with ‘’ or “” • Useful functions [Ref] http://www.php.net/manual/en/ref.strings.php • Getting Properties • strlen(string) – Get string length. • Example $str = 'abcdef';echo strlen($str); // 6$str = ' ab cd ';echo strlen($str); // 7
Functions of Strings (2) • Transformation • trim, ltrim, rtrim, chop – Strip whitespace of a string. • trim – From the beginning and end of a string. • ltrim – From the beginning of a string. • rtrim – From the end of a string. • chop – The same with rtrim. • strtolower, strtoupper – Make a string lowercase/uppsercase. • strrev – Reverse a string. • str_repeat(string, times) – Repeat string $times times. • Example echo strrev("Hello world!"); // outputs "!dlrow olleH" $text = "\t\tA few words :) ... ";echo trim($text); // "A few words :) ..."echo trim($text, " \t."); // “A few words :)" $str = “HELLO";$str = strtolower($str);echo $str; // hello echo str_repeat("-=", 5); // outputs “-=-=-=-=-=“
Functions of Strings (3) • Searching/Tokenizing • substr – Return part of a string. • strpos, strrpos – Find position of first/last occurrence of a string. • strstr, stristr, strchr, strrchr • Return remaining sub-string while matching first/last occurrence of a string. • substr_count – Count the number of substring occurrences. • Example echo substr('abcdef', 1); // bcdefecho substr('abcdef', 1, 3); // bcdecho substr('abcdef', 0, 4); // abcdecho substr('abcdef', 0, 8); // abcdefecho substr('abcdef', -1, 1); // f $email = 'user@example.com';$domain = strstr($email, '@');echo $domain; // prints @example.com $text = 'This is a test'; echo substr_count($text, 'is'); // 2 $newstring = 'abcdef';$pos = strpos($newstring, 'a'); // $pos = 0
Functions of Strings (4) • Practicing • 1. Find length of this String. • 2. Strip head/end whitespace of this String and show length. • 3. Make this String to uppercase and print it. • 4. Print first 20 character of this string. • 5. Find ‘enables’ first occurrence position. “ WaSP issues an open invitation to work with Assistive Technology Vendors to help ensure greater support for standards-based web development techniques in software that enables access for millions of people worldwide. “ http://tphp.cs.nctu.edu.tw/tphp/pr3_4_string.txt http://tphp.cs.nctu.edu.tw/tphp/pr3-4_1.php http://tphp.cs.nctu.edu.tw/tphp/pr3-4_1.txt http://tphp.cs.nctu.edu.tw/tphp/pr3-4_2.php http://tphp.cs.nctu.edu.tw/tphp/pr3-4_2.txt http://tphp.cs.nctu.edu.tw/tphp/pr3-4_3.php http://tphp.cs.nctu.edu.tw/tphp/pr3-4_3.txt http://tphp.cs.nctu.edu.tw/tphp/pr3-4_4.php http://tphp.cs.nctu.edu.tw/tphp/pr3-4_4.txt http://tphp.cs.nctu.edu.tw/tphp/pr3-4_5.php http://tphp.cs.nctu.edu.tw/tphp/pr3-4_5.txt
Functions of Strings (5) • Further Study: Regular Expression • Functions • ereg, eregi • Regular expression match. • split, spliti • Split string into array by regular expression. • ereg_replace, eregi_replace • Replace regular expression. • preg_* • Using perl-compatible regular expression.
Functions of Strings (6) • Example $date = “2006-11-12”; if (ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $date, $regs)) { echo "$regs[3].$regs[2].$regs[1]"; // outputs “12.11.2006” } else { echo "Invalid date format: $date";} $date = "04/30/1973";list($month, $day, $year) = split('[/]', $date);echo "Month: $month, Day: $day; Year: $year<br />\n"; // outputs “Month:04, Day: 30, Year: 1973”; $string = "This is a test";echo str_replace(" is", " was", $string); // outputs “This was a test”echo ereg_replace("( )is", "\\1was", $string); // outputs “This was a test” echo ereg_replace("(( )is)", "\\2was", $string); // outputs “This was a test”
method variables method method method Object Oriented (1) • PHP supports OOP (Object-Oriented Programming) • Basic Properties of Object • State member data • Behavior member functions • Identity object name (like variable name) • OOP • Languages that supports 3 object-oriented characteristics. • Encapsulation • Encapsulate variables & functions to be an object. • Inheritance • Reuse existing objects. • Polymorphism • Using same code handling different types of data types.
Object Oriented (2) • Class and Object • Class • The blueprint of object • Contains the definition of “member data” and “member functions” • Defining Classes classclassname { var $var1; var $var2, $var3; function __construct ($invar1, $invar2, …){ …} function __destruct () {…} function member_func ($invarx, $invary, …) {…} } • Creating Objects $obj = newclassname($arg1, $arg2, …);
Object Oriented (3) • Example class Student { var $id, $name; function setid($newid){ //do nothing } } $s1 = new Student(); print_r ($s1); • student Object • ( • [id] => • [name] => • )
Object Oriented (4) • Accessing member data & Calling member function • Inner object Member data: $this -> varname Member function: $this -> member_fun($arg1, $arg2, …) • Out of object Member data: $obj -> varname Member function: $obj -> member_fun($arg1, $arg2, …)
Object Oriented (5) • Example class Student { var $id, $name; function setid($newid){ $this->id = $newid; } function getid(){ return $this->id; } } $s1 = new Student(); $s2 = new Student(); $s1->id = "9412345"; echo "Student1 ID:", $s1->id; // output 9412345 $s2->setid("9654321"); echo "Student2 ID:", $s2->getid(); // output 9654321
Object Oriented (6) • Constructor and Destructor • Constructor • The initial function object generated. function __constructor ($invar1, $invar2, …) { … } • Destructor • The final function before object die. function __destructor () { … } • There are no return values in both constructors and destructors.
Object Oriented (7) • Example class MyDestructableClass { function __construct() { print "In constructor\n"; $this->name = "MyDestructableClass"; } function __destruct() { print "Destroying " . $this->name . "\n"; }}$obj = new MyDestructableClass(); In constructor Destroying MyDestructableClass
Object Oriented (8) • Visibility of member data/functions • private • Only visible inner class itself. • public • Visible everywhere. • protected • Visible in itself and classes inherit this class.
Object Oriented (9) • Example class MyClass{ public $public = 'Public'; protected $protected = 'Protected'; private $private = 'Private'; function printHello() { echo $this->public; echo $this->protected; echo $this->private; }}$obj = new MyClass();echo $obj->public; // Worksecho $obj->protected; // Fatal Errorecho $obj->private; // Fatal Error$obj->printHello(); // Shows Public, Protected and Private class MyClass2 extends MyClass{ function printHello() { echo $this->public; echo $this->protected; echo $this->private; }}$obj2 = new MyClass2();echo $obj->public; // Worksecho $obj2->private; // Undefined (not error)echo $obj2->protected; // Fatal Error$obj2->printHello(); // Shows Public, Protected, not Private
Object Oriented (10) • Class constant • Syntax: class classname { constCONSTNAME = value; } • Accessing • Inner object • self::CONSTNAME • Out of object • classname::CONSTNAME
Object Oriented (11) • Static member data/functions • Syntax: class classname { public static $VARIABLE = value; public static function METHOD() { ……… } } • Accessing • Inner object • self::$VARIABLE • self::METHOD() • Out of object • classname::$VARIABLE • classname::METHOD()
Object Oriented (12) • Example class Foo{ public static $my_static = 'foo'; public function staticValue() { return self::$my_static; }}class Bar extends Foo{ public function fooStatic() { return parent::$my_static; }}print Foo::$my_static . "\n";$foo = new Foo();print $foo->staticValue() . "\n";print $foo->my_static . "\n"; // Undefined "Property" my_static // $foo::my_static is not possibleprint Bar::$my_static . "\n";$bar = new Bar();print $bar->fooStatic() . "\n"; class MyClass{ const constant = 'constant value'; function showConstant() { echo self::constant . "\n"; }}echo MyClass::constant . "\n";$class = new MyClass();$class->showConstant();// echo $class::constant; is not allowed class Foo { public static function aStaticMethod() { // ... }}Foo::aStaticMethod();
Object Oriented (13) • Priacticing • Make a Class “Book” who has members: “code”, “title”, “author”, “price”. Make a constructor function, a function BookCounts() to get how many books there and a function showBook() to print information of a Book. The Book Maximum num is 50. http://tphp.cs.nctu.edu.tw/tphp/pr3-5.php http://tphp.cs.nctu.edu.tw/tphp/pr3-5.txt
Object Oriented (14) • Further Study • Inheritance class classnameextendsparent_class { … } • Polymorphism • abstract & interface
Exception Handling (1) • Exceptions (Errors) • Reason • Environmental • Programming • Levels • Parse Errors • Fatal Errors • Warnings • Notices
Exception Handling (2) • Exception Handling • Error Reporting • Setting what will be reported:error_reporting ( ERR1 | ERR2 | … ); • ERRORS ( Predefined Constants) • E_ALL • E_ERROR, E_WARNING, E_PARSE, E_NOTICE • E_CORE_ERROR, E_CORE_WARNING • E_COMPILE_ERROR, E_COMPILE_WARNING • E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE • E_STRICT ( PHP ≧ 5.0) • E_RECOVERABLE_ERROR ( PHP ≧ 5.2)
Exception Handling (3) • Error Handler • Setting who (function) will handle errors:set_error_handler(‘handlername’); function handlername($type, $msg, $file, $line) { // $type is error level // $msg is error info // $file is the php filename executed // $line is the line number of code when error happened. }
Exception Handling (4) • Logging Errors • Error handler can keep logs somewhere he want. • Setting where to keep logs:error_log($msg, OUTPUT_TYPE, $target); • OUTPUT_TYPE • 0 Log to system log • 1 Log mailed to $target (should be an email address) • 3 Log to $target (should be a file)
Exception Handling (5) • User Level Errors • User can create some errors in the programs. • Generating user level error:trigger_error($msg, ERROR); • ERROR available • E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE
Exception Handling (6) • Example // set the error reporting level for this scripterror_reporting(E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE);// error handler functionset_error_handler(“myErrorHandler”); function myErrorHandler($errno, $errstr, $errfile, $errline) { switch ($errno) { case E_USER_ERROR: echo "<b>My ERROR</b> [$errno] $errstr<br />\n"; echo " Fatal error in line $errline of file $errfile"; echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n"; echo "Aborting...<br />\n"; exit(1); break; case E_USER_WARNING: echo "<b>My WARNING</b> [$errno] $errstr<br />\n"; break; case E_USER_NOTICE: echo "<b>My NOTICE</b> [$errno] $errstr<br />\n"; break; default: echo "Unknown error type: [$errno] $errstr<br />\n"; break; }}
Exception Handling (7) • Example 2 // Send notification through the server log if we can not// connect to the database.if (!Ora_Logon($username, $password)) {error_log("Oracle database not available!", 0);}// Notify administrator by email if we run out of FOOif (!($foo = allocate_new_foo())) {error_log("Big trouble, we're all out of FOOs!", 1, "operator@example.com");}// other ways of calling error_log():error_log("You messed up!", 2, "127.0.0.1:7000");error_log("You messed up!", 2, "loghost");error_log("You messed up!", 3, "/var/tmp/my-errors.log"); if (assert($divisor == 0)) {trigger_error("Cannot divide by zero", E_USER_ERROR);}