Presentation is loading. Please wait.

Presentation is loading. Please wait.

V 1.0 OE NIK 2013 1 PHP+SQL 3. Arrays Array functions Practice.

Similar presentations


Presentation on theme: "V 1.0 OE NIK 2013 1 PHP+SQL 3. Arrays Array functions Practice."— Presentation transcript:

1 V 1.0 OE NIK PHP+SQL 3. Arrays Array functions Practice

2 V 1.0 OE NIK PHP+SQL 3. Arrays Array functions Practice

3 V 1.0 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) 3 OE NIK 2013

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

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

6 V 1.0 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) 6 OE NIK 2013

7 V 1.0 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! 7 OE NIK 2013

8 V 1.0 Foreach loop "Bill"); foreach ($x as $my_key => $my_value) { echo "{$my_key} is {$my_value } "; } ?> 8 OE NIK 2013 foreach ($array as $key=>$value) { // Code to be executed }

9 V 1.0 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; 9 OE NIK 2013

10 V 1.0 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); array(3) { [0]=> string(4) "hihi" ["eleven"]=> int(11) ["subarray"]=> array(3) { [4]=> string(12) "Some content" ["a"]=> string(1) "b" [5]=> int(44) } 10 OE NIK 2013

11 V 1.0 OE NIK PHP+SQL 3. Arrays Array functions Practice

12 V 1.0 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 12 OE NIK 2013

13 V 1.0 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) } 13 OE NIK 2013

14 V 1.0 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) } 14 OE NIK 2013

15 V 1.0 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 +) 15 OE NIK 2013

16 V 1.0 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 16 OE NIK 2013

17 V 1.0 usort "Bill", "age"=>10); array("name"=>"Joe", "age"=>8) ); usort($kids, "cmp"); ?> 17 OE NIK 2013

18 V 1.0 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 18 OE NIK 2013

19 V 1.0 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) 19 OE NIK 2013

20 V 1.0 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

21 V 1.0 OE NIK PHP+SQL 3. Arrays Array functions Practice

22 V 1.0 Exercise #1 Generate random arrays: the arrays' size should be fixed, the arrays should contain random Integers Floating point numbers Characters Strings Names 22 OE NIK 2013

23 V 1.0 Example: form.html Name: Age: GET vs POST 23 OE NIK 2013

24 V 1.0 Example: welcome.php Welcome ! You are years old. "; echo "You are {$_POST['age']} old! "; ?> 24 OE NIK 2013

25 V 1.0 Exercise #2 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 25 OE NIK 2013

26 V 1.0 Exercise #3 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 HW! 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!) 26 OE NIK 2013

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

28 V 1.0 Practice exercises Determine the monthly average! 28 OE NIK 2013 We have the daily average temperatures in an array. Answer the following questions! 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?

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

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

31 V 1.0 Practice exercises 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 31 OE NIK 2013

32 V 1.0 Practice exercises 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!) 32 OE NIK 2013

33 V 1.0 OE NIK

34 34 OE NIK 2013


Download ppt "V 1.0 OE NIK 2013 1 PHP+SQL 3. Arrays Array functions Practice."

Similar presentations


Ads by Google