Arrays Array functions Practice

Slides:



Advertisements
Similar presentations
PHP Form and File Handling
Advertisements

PHP I.
UFCE8V-20-3 Information Systems Development 3 (SHAPE HK) Lecture 3 PHP (2) : Functions, User Defined Functions & Environment Variables.
Lecture 6/2/12. Forms and PHP The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input When dealing with HTML forms.
V 1.0 OE NIK PHP+SQL 3. Arrays Array functions Practice.
NUMERIC ARRAYS DEBBI HAMNER CIT 336 TEACHING PRESENTATION.
PHP (2) – Functions, Arrays, Databases, and sessions.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
INTERNET APPLICATION DEVELOPMENT For More visit:
PHP Arrays. Outline o What is array in PHP ? o Numeric array o Associative array o Multidimensional array.
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
PHP - Introduction Week 5 Dr. Ken Cosh Introducing PHP 1.
Open Source Software Unit – 3 Presented By Mr. R.Aravindhan.
Introduction to PHP – Part 2 Sudeshna Dey. Arrays A series of homogeneous elements Elements have values in form of stored data Has a key associated with.
Web Programming Language Week 5 Dr. Ken Cosh Introducing PHP 1.
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
הרצאה 4. עיבוד של דף אינטרנט דינמי מתוך Murach’s PHP and MySQL by Joel Murach and Ray Harris.  דף אינטרנט דינמי משתנה עפ " י הרצת קוד על השרת, יכול להשתנות.
CHAPTER 7 Introduction to PHP5 Part II อ. ยืนยง กันทะเนตร คณะเทคโนโลยีสารสนเทศและการสื่อสาร มหาวิทยาลัยพะเยา 1.
NMD202 Web Scripting Week2. Web site
Unit-6 Handling Sessions and Cookies. Concept of Session Session values are store in server side not in user’s machine. A session is available as long.
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
11 – Introduction to PHP(1) Informatics Department Parahyangan Catholic University.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
CGS 3066: Web Programming and Design Spring 2016 PHP.
PHP. What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server.
Simple PHP Web Applications Server Environment
Lesson 4 String Manipulation. Lesson 4 In many applications you will need to do some kind of manipulation or parsing of strings, whether you are Attempting.
Lesson 3 Functions. Lesson 3 Functions are declared with function. For example, to calculate the cube of a number function function name (parameters)
Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.
CGS 3066: Web Programming and Design Spring 2017
CHAPTER 5 SERVER SIDE SCRIPTING
PHP (Session 1) INFO 257 Supplement.
Receiving form Variables
REPETITION CONTROL STRUCTURE
A bit of C programming Lecture 3 Uli Raich.
เอกสารประกอบการบรรยายรายวิชา Web Technology
CIIT-Human Computer Interaction-CSC456-Fall-2015-Mr
Arrays: Checkboxes and Textareas
DBW - PHP DBW2017.
Arrays in PHP are quite versatile
CHAPTER 5 SERVER SIDE SCRIPTING
Web Technologies PHP 5 Basic Language.
PHP Functions Besides the built-in PHP functions, we can create our own functions. A function is a block of statements that can be used repeatedly in.
19.10 Using Cookies A cookie is a piece of information that’s stored by a server in a text file on a client’s computer to maintain information about.
Chapter 19 PHP Part III Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice Hall ©
1 CHAPTER 10 ADVANCED PHP.
Introduction to Web programming
Chapter 19 PHP Part II Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice Hall ©
8th Semester, Batch 2008 Department of Computer Science SSUET.
PHP FORM HANDLING Post Method
Arrays in C.
Intro to PHP & Variables
ITS332.
Basic PHP Lecture by Nutthapat Keawrattanapat
Ch. 3. PHP (이 강의 내용의 대부분 예들은 w3schools. com/php/default
<?php require("header.htm"); ?>
Web Systems Development (CSC-215)
PHP.
Data Structures (CS212D) Week # 2: Arrays.
HYPERTEXT PREPROCESSOR BY : UMA KAKKAR
Basics (Cont...).
Arrays Week 2.
Web Programming Language
PHP PART 2.
PHP an introduction.
PHP PROF. S. LAKSHMANAN, DEPT. OF B. VOC. (SD & SA),
PHP Lecture 11 Kanida Sinmai
PHP-II.
Presentation transcript:

Arrays Array functions Practice PHP+SQL 2. Arrays Array functions Practice OE NIK 2013

Arrays Array functions Practice PHP+SQL 2. Arrays Array functions Practice OE NIK 2013

Arrays Numeric array / Indexed array – Elements can be accessed using numerical indices – usually direct memory-mapped array Associative array – Elements are basically key-value pairs, much more flexible, but a lot slower Multidimensional array – In case of memory mapped array: matrix or jagged array. With associative arrays: An array that has other arrays as some of the values The biggest strength of PHP is that it has a reasonably good associative array type (not too fast, but extremely good functions ... alternative: splFixedArray) OE NIK 2013

Numeric array $cars=array("Saab","Volvo","BMW", "Toyota"); $cars=array(); $cars[0]="Saab"; $cars[1]="Volvo"; $cars[2]="BMW"; $cars[3]="Toyota"; $cars[]="Fiat"; OE NIK 2013

Associative array (key=>value pairs) $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34); $ages=array(); $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; OE NIK 2013

SUPERGLOBALS (these arrays can always be accessed from anywhere, without the usage of global keyword) $GLOBALS — Contains all use variables from the global scope $_GET — HTTP GET variables $_POST — HTTP POST variables $_FILES — HTTP File upload information (excluding the file content) $_SESSION — Session variables (server-side storage) $_COOKIE — HTTP „cookies” (client-side storage) OE NIK 2013

SUPERGLOBALS $_REQUEST — HTTP Request variables (= GET + POST) $_ENV — Environmental variables $_SERVER — Information about the server and the execution environment $HTTP_RAW_POST_DATA — Unprocessed POST data $php_errormsg — The last PHP error message $http_response_header — Unprocessed raw HTTP response header-lines $argc — Number of command line arguments (CLI only) $argv — Values of command line arguments (CLI only) register_globals: EGPCS (Environment, GET, POST, Cookie, Server) – default OFF since PHP 4.3, not possible since PHP 6, AVOID! OE NIK 2013

Foreach loop foreach ($array as $key=>$value) {    // Code to be executed } <html> <body> <?php $x=array("zero", "one", "two", "the_king"=>"Bill"); foreach ($x as $my_key => $my_value) {   echo "{$my_key} is {$my_value }<br />"; } ?> </body> </html> OE NIK 2013

Multi-dimensional array Any of the values can be an array (the keys cannot!) $x=array(); //empty array $x[] = 10; // Using numerical index, new element: $x[0]=10 $x['eleven'] = 11; //Associative key-value pair $x['0']="hihi"; //'0' == 0, so this overwrites the previous value $a = array (2 => "Bill is the king"); $a[] = 42; // Using numerical index, new element: $a[3]=42; $a = array (4 => "Some content", ’a’ => ’b’); $a[] = 44; // Using numerical index, new element: $a[5]=44; $x['subarray']=$a; OE NIK 2013

print_r($x); var_dump($x); array(3) { [0]=> string(4) "hihi" ["eleven"]=> int(11) ["subarray"]=> [4]=> string(12) "Some content" ["a"]=> string(1) "b" [5]=> int(44) } print_r($x); Array ( [0] => hihi [eleven] => 11 [subarray] => Array [4] => Some content [a] => b [5] => 44 ) $y=print_r($x, true) ; var_dump($x); OE NIK 2013

Arrays Array functions Practice PHP+SQL 2. Arrays Array functions Practice OE NIK 2013

Array operator + $a = array (1, 2, 3); $b = array (’a’ => 1, ’b’ => 2, ’c’ => 3); var_dump ($a + $b); array(6) { [0]=> int(1) [1]=> int(2) [2]=> int(3) ["a"]=> int(1) ["b"]=> int(2) ["c"]=> int(3) } The resulting array contains all elements from both arrays, because the associative keys are different OE NIK 2013

Union With numerical indices or with same associative keys, the result is the mathematical union (with numerical indices: even if the indices are different!) $a = array (1, 2, 3); $b = array (’a’ => 1, 2, 3); var_dump ($a + $b); array(4) { [0]=> int(1) [1]=> int(2) [2]=> int(3) ["a"]=> int(1) } OE NIK 2013

array_merge $a = array (1, 2, 3); $b = array ("a" => 1, 2, 3); var_dump (array_merge($a, $b)); array(6) { [0]=> int(1) [1]=> int(2) [2]=> int(3) ["a"]=> int(1) [3]=> int(2) [4]=> int(3) } OE NIK 2013

Array functions count() , is_array(), isset(), array_key_exists(), in_array(), unset(), array_merge() array_push(), array_pop(), array_shift(), array_unshift() (STACK and QUEUE data structures are possible) array_diff(), array_intersect() (the union is the operator +) OE NIK 2013

Sorting an array shuffle() – randomly sort the elements sort() , rsort() – according to values, renumbers keys asort(), arsort() – according to values, associative ksort(), krsort() – according to keys usort() – according to values using a user function, renumbers keys uasort() – according to values using a user function, associative uksort() – according to keys using a user function OE NIK 2013

usort <?php function cmp($a, $b) { if ($a["age"] == $b["age"]) { return 0; } return ($a["age"] < $b["age"]) ? -1 : 1; $kids=array( array("name"=>"Bill", "age"=>10); array("name"=>"Joe", "age"=>8) ); usort($kids, "cmp"); ?> OE NIK 2013

Special string functions str_replace() function: change multiple values in a string, a very commonly used function! $result=str_replace($from, $to, $source); echo str_replace("World", "Reader", "Hello World"); echo str_replace(array("Hello", "World"), array("Bonjour", "Monde"), "Hello World"); // Bonjour Monde echo str_replace(array("Hello", "World"), "Bye", "Hello World"); // Bye Bye Fast, thought the sprintf() is about twice as fast, but it knows less OE NIK 2013

Special string functions strtr() function: Simple transformations $result=strtr($source, $from, $to); $result=strtr($source, $changearray); $addr = strtr($addr, "äåö", "aao"); $trans = array("hello" => "hi", "hi" => "hello"); echo strtr("hi all, I said hello", $trans); //hello all, I said hi Problem: simpler operation, but VERY slow (~50x slower than the str_replace) OE NIK 2013

Special string functions preg_replace(), ereg_replace(), preg_match() preg_replace($pattern, $replace, $source) Regular expressions (not needed, thought it knows the most) Complicated, but complex pattern matching and exchanges are possible Pattern matching: similarity instead of equality All-knowing, pattern matching, but little slow (the str_replace is ~2x faster) OE NIK 2013

Arrays Array functions Practice PHP+SQL 2. Arrays Array functions Practice OE NIK 2013

Example: form.html <html><body> <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body></html> GET vs POST OE NIK 2013

Example: welcome.php <html><body> Welcome <?php echo $_POST["fname"]; ?>! <br /> You are <?php echo $_POST["age"]; ?> years old. </body></html>   <?php echo "Welcome {$_POST['fname']}!<br />"; echo "You are {$_POST['age']} old!<br />"; // OR: str_replace/TWIG magic! ?> OE NIK 2013

Example: symfony, html <!-- html/nameinput.html --> <form action="/nameprocess" method="POST"> Name: <input type="text" name="fname" /> <br /> Age: <input type="text" name="age" /> <br /> <input type="submit" value="SEND" /> </form> <!-- html/nameprocess.html --> <p> Hello {{ FNAME }} you are {{ AGE }} years old </p> OE NIK 2013

Example: symfony, display /** * @Route("/nameinput", name="formRoute") */ public function nameinputForm(Request $request) { $output=file_get_contents( "../html/nameinput.html"); return new Response($output); } OE NIK 2013

Example: symfony, process /** * @Route("/nameprocess", name="processRoute") */ public function nameinputProcess(Request $request) { $output=file_get_contents( "../html/nameprocess.html"); $fname = $request->request->get("fname", "NA"); $age = $request->request->get("age", -1); $fname=strip_tags($fname); // CSRF? XSS? HTMLawed? HTMLPurifier? $age=strip_tags($age); $output = str_replace("{{ FNAME }}", $fname, $output); $output = str_replace("{{ AGE }}", $age, $output); return new Response($output); } OE NIK 2013

Exercise #1 Let's write a basic calculator! The data input should be done using an HTML form (calculator.html) : operand1 (textbox), operand2 (textbox), operator (+ - * /, select). The processing should be done by a PHP script (calculator.php), the script's output should be the result of the operation (or an error message, according to the error) In addition, display a link that points back to the form OE NIK 2013

Exercise #2 You have to create a page where the visitors can vote for their favourite songs $lines = file(“songs.txt”); file_put_contents(“X\n”, “votes.txt”, FILE_APPEND); Manually create a file songs.txt that contains the available songs (1 song/line) /songs/form  display a form to input a name, an email address, and a favourite song /songs/vote  store the form input to songvotes.txt /songs/lottery  one random voter receives a prize, so write out all data of one voter /songs/favourite  write out the favorite song (the one with the biggest number of votes) OE NIK 2013

Practice Exercise (dynamic HTML generation) The user must enter a number (X), and after this, we should display a form where the user can enter X other numbers. Determine the average of the input values Decide if the given input has a prime number or not Do the same for two matrices: ask for the number or rows+columns ; input the two matrices ; then display the matrices nicely along with the result of their multiplication (error handling!) OE NIK 2013

Practice Exercise (arrays) Generate random arrays: the arrays' size should be fixed, the arrays should contain random Integers Floating point numbers Characters Strings Names OE NIK 2013

Practice exercises (arrays) Copy out an arbitrary, long enough text from the Internet Determine: How many times the different words occur in the text (word + number of occurrences, sorted by the prevalence) The most frequent word The length of the longest word (two solutions: with and without the previously generated array!) OE NIK 2013

Practice exercises (arrays) Generate a random array that will store the test results for a group of students (in percentage, integers, 0..100) Answer the following questions! Determine the group's average percentage! Is there anyone who failed (below 51%) How small is the worst result? How many students got the best grade? (88% or above) Create a statistics based off the grades! OE NIK 2013

Practice exercises (arrays) We have the daily average temperatures in an array. Answer the following questions! Determine the monthly average! Did it freeze in this month? Search a day where the temperature was below 5 degrees! How many days are in the sample where the temperature was below the average? How many degrees were on the hottest day? OE NIK 2013

Practice exercises (arrays) Ask a sentence from the user. Using that sentence, answer the following questions! Count the number of syllables! (Tip: num of vowels=num of syllables) Select the uppercase letters from the text! (Tip: ctype_upper() function) Do we have at least three 'a' letters? If yes: where is the third? Do we have at least ten consecutive 'a' letters? Copy the text so that you change every 'x' to 'X'! OE NIK 2013

Practice exercises (arrays) Using a randomly created integer array, solve the following exercises! Determine the number of minimums and maximums! Sum up the even numbers! Select out the primes from the array! Separate the array elements according to whether they are smaller than the average or not. OE NIK 2013

Practice exercises (arrays) An airplane is flying in a straight line, and meanwhile it's doing measurements: it stores the height of the area below the plane. The results are stored in a 1D array (let's generate this randomly): 0 means that there is sea, anything bigger than zero means an island Determine The height of the biggest hill The number of occurrences for that height The length of the longest island OE NIK 2013

OE NIK 2013

OE NIK 2013