Associative Arrays and Strings Associative Arrays Strings and
- Slides: 46
Associative Arrays and Strings Associative Arrays, Strings and String Operations Soft. Uni Team Technical Trainers Software University http: //softuni. bg
Table of Contents 1. Associative Arrays § Array Manipulation § Multidimensional Arrays 2. Strings § String Manipulation § Regular Expressions 2
Questions sli. do #PHPFUND 3
Associative Arrays
Associative Arrays (Maps, Dictionaries) § Associative arrays are arrays indexed by keys § Not by the numbers 0, 1, 2, 3, … § Hold a set of pairs <key, value> § Traditional array § Associative array key 0 1 value 8 -3 2 3 4 12 408 33 orange apple tomato value 2. 30 1. 50 3. 80 5
Phonebook – Associative Array Example $phonebook = []; $phonebook["John Smith"] = "+1 -555 -8976"; // Add $phonebook["Lisa Smith"] = "+1 -555 -1234"; $phonebook["Sam Doe"] = "+1 -555 -5030"; $phonebook["Nakov"] = "+359 -899 -555 -592"; $phonebook["Nakov"] = "+359 -2 -9819"; // unset($phonebook["John Smith"]); // Delete echo count($phonebook); // 3 6
Associative Arrays in PHP § Initializing an associative array: $people = array( 'Gero' => '0888 -257124', 'Pencho' => '0888 -3188822'); § Accessing elements by index: echo $people['Pencho']; // 0888 -3188822 § Inserting / deleting elements: $people['Gosho'] = '0237 -51713'; // Add 'Gosho' unset($people['Pencho']); // Remove 'Pencho' print_r($people); // Array([Gero] => 0888 -257124 [Gosho] => 0237 -51713) 7
Iterating Through Associative Arrays § foreach ($array as $key => $value) § Iterates through each of the key-value pairs in the array $greetings = ['UK' => 'Good morning', 'France' => 'Bonjour', 'Germany' => 'Guten Tag', 'Bulgaria' => 'Ko staa']; foreach ($greetings as $key => $value) { echo "In $key people say "$value". "; echo " "; } 8
Problem: Sum by Town § Read towns and incomes (like shown below) and print a array holding the total income for each town (see below) Sofia 20 Varna 3 Sofia 5 Varna 4 § Print the towns in their natural order as object properties ["Sofia" => "25", "Varna" => "7"] 9
Solution: Sum of Towns $arr = ['Sofia', '20', 'Varna', '10', 'Sofia', '5 ']; $sums = []; for ($i = 0; $i < count($arr); $i += 2) { list($town, $income) = [$arr[$i], $arr[$i+1]]; if ( ! isset($sums[$town])) $sums[$town] = $income; else $sums[$town] += $income; list($town, . . ) } Assign variables as if print_r($sums); they were an array 10
Problem: Counting Letters in Text $text = "Learning PHP is fun! "; $letters = []; $text = strtoupper($text); for ($i = 0; $i < strlen($text); $i++) { $char = $text[$i]; if (ord($char) >= ord('A') && ord($char) <= ord('Z')) { if (isset($letters[$char])) { $letters[$char]++; isset($array[$i]) } else { checks if the key exists $letters[$char] = 1; } } } print_r($letters); 11
Practice: Associative Arrays Live Exercises in Class (Lab)
Strings
Strings § A string is a sequence of characters § Can be assigned a literal constant or a variable § Text can be enclosed in single (' ') or double quotes (" ") <? php $person = '<span class="person">Mr. Svetlin Nakov</span>'; $company = "<span class='company'>Software University</span>"; echo $person. ' works @ '. $company; ? > § Strings in PHP are mutable § Therefore concatenation is a relatively fast operation 14
String Syntax § Single quotes are acceptable in double quoted strings echo "<p>I'm a Software Developer</p>"; § Double quotes are acceptable in single quoted strings echo '<span>At "Software University"</span>'; § Variables in double quotes are replaced with their value $name = 'Nakov'; $age = 25; $text = "I'm $name and I'm $age years old. "; echo $text; // I'm Nakov and I'm 25 years old. 15
Interpolating Variables in Strings § Simple string interpolation syntax § Directly calling variables in double quotation marks (e. g. "$str") § Complex string interpolation syntax § Calling variables inside curly parentheses (e. g. "{$str}") § Useful when separating variable from text after $popular. Name = "Pesho"; echo "This is $popular. Name. "; // This is Pesho. echo "These are {$popular. Names}s. "; // These are Peshos. 16
Heredoc Syntax § Heredoc syntax <<<"EOD". . EOD; $name = "Didko"; $str = <<<"EOD" My name is $name and I am very, very happy. EOD; echo $str; /* My name is Didko and I am very, very happy. */ 17
Nowdoc Syntax § Heredoc syntax <<<'EOD'. . EOD; $name = "Didko"; $str = <<<'EOD' My name is $name and I am very, very happy. EOD; echo $str; /* My name is $name and I am very, very happy. */ 18
String Concatenation § In PHP, there are two operators for combining strings: § Concatenation operator. § Concatenation assignment operator. = <? php $home. Town = "Madan"; $current. Town = "Sofia"; $home. Town. Description = "My home town is ". $home. Town. "n"; $home. Town. Description. = "But now I am in ". $current. Town; echo $home. Town. Description; § The escape character is the backslash 19
Unicode Strings § By default PHP uses the legacy 8 -bit character encoding § Like ASCII, ISO-8859 -1, windows-1251, KOI 8 -R, … § Limited to 256 different characters § You may use Unicode strings as well, but: § Most PHP string functions will work incorrectly § You should use multi-byte string functions § E. g. mb_substr() instead of substr() 20
Problem: Unicode Strings § Print Unicode text and processing it letter by letter: mb_internal_encoding("utf-8"); header('Content-Type: text/html; charset=utf-8'); $str = 'Hello, 你好,你怎么�, ﺍﻟﺴﻼﻡ ﻋﻠﻴﻜﻢ , здрасти'; echo "<p>str = "$str"</p>"; for ($i = 0; $i < mb_strlen($str); $i++) { // $letter = $str[$i]; // this is incorrect! $letter = mb_substr($str, $i, 1); echo "str[$i] = $letter n"; } 21
Problem: Print String Letters § Read a string and print its letters as shown below Soft. Uni str[0] str[1] str[2] str[3] str[4] str[5] str[6] -> -> 'S' 'o' 'f' 't' 'U' 'n' 'i' $str = "Soft. Uni"; if (is_string($str)) { $str. Length = strlen($str); for ($i = 0; $i < $str. Length; $i++){ echo "str[$i]". " -> ". $str[$i]. "n"; } } 22
Practice: Strings Live Exercises in Class (Lab)
Manipulating Strings
Accessing Characters and Substrings § strpos($input, $find) – a case-sensitive search § Returns the index of the first occurrence of string in another string $soliloquy = "To be or not be that is the question. "; echo strpos($soliloquy, "that"); // 16 var_dump(strpos($soliloquy, "nothing")); // bool(false) § strstr($input, $find, [boolean]) – finds the first occurrence of a string and returns everything before or after echo strstr("This is madness!n", "is ") ; // is madness! echo strstr("This is madness!", " is", true); // This 25
Accessing Characters and Substrings (2) § substr($str, $position, $count) – extracts $count characters from the start or end of a string $str echo = "abcdef"; substr($str, 1). "n"; -2). "n"; 0, 3). "n"; -3, 1); // // bcdef ef abc d § $str[$i] – gets a character by index php $str = "Apples"; echo $str[2]; // p 26
Counting Strings § strlen($str) – returns the length of the string echo strlen("Software University"); // 19 § str_word_count($str) – returns the number of words in a text re $countries = "Bulgaria, Brazil, Italy, USA, Germany"; echo str_word_count($countries); // 5 § count_chars($str) – returns an associative array holding the value of all ASCII symbols as keys and their count as values $hi = "Helloooooo"; echo count_chars($hi)[111]; // 6 (o = 111)
Accessing Character ASCII Values § ord($str[$i]) – returns the ASCII value of the character $text = "Call me Banana-man!"; echo ord($text[8]); // 66 § chr($value) – returns the character by ASCII value $text = "Soft. Uni"; for ($i = 0; $i < strlen($text); $i++) { $ascii = ord($text[$i]); $text[$i] = chr($ascii + 5); } echo $text; // Xtky. Zsn 28
String Replacing § str_replace($target, $replace, $str) – replaces all occurrences of the target string with the replacement string $email = "bignakov@example. com"; $new. Email = str_replace("bignakov", "juniornakov", $email); echo $new. Email; // juniornakov@example. com § str_ireplace($target, $replace, $str) str - case-insensitive replacing $text = "Ha. HAha. HAHhaha"; $i. Replace = str_ireplace("A", "o", $text); echo $i. Replace; // Ho. Hoho. Hhoho
Splitting Strings § str_split($str, $length) – splits each character into a string and returns an array § $length specifies the length of the pieces $text = "Hello how are you? "; $arr. Split = str_split($text, 5); var_export($arr. Split); // array ( 0 => 'Hello', 1 => ' how ', 2 => 'are y', 3 => 'ou? ', ) § explode($delimiter, $string) – splits a string by a string echo var_export(explode(" ", "Hello how are you? ")); // array ( 0 => 'Hello', 1 => 'how', 2 => 'are', 3 => 'you? ', ) 30
Case Changing § strtolower() – makes a string lowercase php $lan = "Java. Script"; echo strtolower($lan); // javascript § strtoupper() – makes a string uppercase php $name = "parcal"; echo strtoupper($name); // PARCAL § $str[$i] – access / change any character by index $str = "Hello"; $str[1] = 'a'; echo $str; // Hallo 31
Other String Functions § strcasecmp($string 1, $string 2) § Performs a case-insensitive string comparison § strcmp() – performs a case-sensitive comparison echo !strcmp("h. ELLo", "hello") ? "true" : "false"; // false § trim($text) – strips whitespace (or other characters) from the beginning and end of a string $boo echo = " "it's trim($boo); wide in here" "; // "it's wide in here" 32
Problem: Concatenate and Reverse Strings § Read an array of strings, concatenate them and reverse them I am student tnedutsma. I $array = ['I', 'am', 'student']; if (is_array($array)) { $result = implode("", $array); echo strrev($result); } Reverse a string 33
Practice: Manipulating Strings Live Exercises in Class (Lab)
Regular Expressions Splitting, Replacing, Matching
Regular Expressions § Regular expressions match text by pattern, e. g. : § [0 -9]+ matches a non-empty sequence of digits § [a-z. A-Z]* matches a sequence of letters (including empty) § [A-Z][a-z]+ first name + space + last name § s+ matches any whitespace; S+ matches non-whitespace § d+ matches digits; D+ matches non-digits § w+ matches letters (Unicode); W+ matches non-letters § +d{1, 3}([ -]*[0 -9]+)+ matches international phone § Test your regular expressions at http: //regexr. com 36
Splitting with Regex § preg_split($pattern, $str, $limit, $flags) § Splits a string by a regex pattern § $limit specifies the number of returned substrings (-1 == no limit) § $flags specify additional operations (e. g. PREG_SPLIT_NO_EMPTY) $text = "I love HTML, CSS, PHP and My. SQL. "; $tokens = preg_split("/W+/", $text, -1, PREG_SPLIT_NO_EMPTY); echo json_encode($tokens); Splits by 1 or more // ["I", "love", "HTML", "CSS", "PHP", "and", "My. SQL"] non-word characters 37
Single Match vs Global Match § preg_match – Perform a regular expression match § preg_match_all - Perform a global regular expression match preg_match("/find[ ]*(me)/", "find me", $matches); print_r($matches); preg_match_all("/find[ ]*(me)/", "find me", $matches); print_r($matches); 38
Replacing with Regex § preg_replace($pattern, $replace, $str) – performs a regular expression search and replace by a pattern $string = 'August 20, 2014'; $pattern = '/(w+) (d+), (d+)/'; $replacement = '2 -1 -3'; echo preg_replace($pattern, $replacement, $string); // 20 -August-2014 § () – defines the groups that should be returned as result § 1 – denotes the first match group, 2 – the second, etc. 39
Problem: Email Validation § Perform simple email validation § An email consists of: username @ domain name § Usernames are alphanumeric § Domain names consist of two strings, separated by a period § Domain names may contain only English letters § Valid: valid 123@email. bg § Invalid: invalid*name@emai 1. bg 40
Solution: Email Validation $email = "bai. ivan@mail. sf. net"; $pattern = "/^[a-z. A-Z 0 -9. _]+@[a-z]+(. [az]+)+$/"; $result = preg_match_all($pattern, $email); if ($result) { Returns the number of echo "Valid"; full pattern matches } else { if the email matches the pattern echo "Invalid"; } 41
Practice: Regular Expressions Live Exercises in Class (Lab)
Summary § PHP supports associative arrays § Strings in PHP are non-Unicode § Many built-in functions: strlen() and substr() § Regular expressions are powerful in string processing § preg_split(), preg_replace(), preg_match_all() 43
Associative Arrays and Strings ? s n o i t s e u Q ? ? ? https: //softuni. bg/courses/php-basics/
License § This course (slides, examples, demos, videos, homework, etc. ) is licensed under the "Creative Commons Attribution. Non. Commercial-Share. Alike 4. 0 International" license § Attribution: this work may contain portions from § "PHP Manual" by The PHP Group under CC-BY license § "PHP and My. SQL Web Development" course by Telerik Academy under CC-BY-NC-SA license 45
Free Trainings @ Software University § Software University Foundation – softuni. org § Software University – High-Quality Education, Profession and Job for Software Developers § softuni. bg § Software University @ Facebook § facebook. com/Software. University § Software University @ You. Tube § youtube. com/Software. University § Software University Forums – forum. softuni. bg
- Non associative learning psychology definition
- Nonassociative learning definition
- Fixed action pattern
- Dynamic arrays and amortized analysis
- Searching and sorting arrays in c++
- Advantages of array
- Elastic strings and springs
- Pointers and strings
- String and other things
- Parallel arrays
- Array of arrays c++
- Parallel arrays
- 潘仁義
- C++ parallel arrays
- Why do we need arrays?
- Arrays unidimensionales java
- Arrays bidimensionales java
- Arrays mips
- Polynomial representation using array in c
- Arrays in arm assembly
- Global arrays in c
- Computer science arrays
- Arrays visual basic
- Python find index of max
- How many arrays in 24
- 2d array pascal
- Dynamic array mips
- Creating arrays matlab
- Array adt
- Partially filled array java
- Redundant arrays of independent disks
- Python list of arrays
- Arrays
- Day 3: arrays
- Redundant arrays of inexpensive disks
- Microsoft small basic
- Disadvantages of static memory allocation
- Microled arrays
- Are vectors dynamic arrays
- Facts about arrays
- Strings in java
- Flexible pattern matching in strings
- Rate of energy transfer by sinusoidal waves on strings
- Python compare strings
- A percussion bar of the ifugaos.
- Michael league gear
- Mrs sprockett's strange machine