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