You are on page 1of 16

Associative Arrays

Associative Arrays
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 value
key 0 1 2 3 4 orange 2.30
value 8 -3 12 408 33 apple 1.50
tomato 3.80
3
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-981-9819"; //

unset(phonebook["John Smith"]); // Delete


echo count(phonebook); // 3
4
Associative Arrays in PHP
 Initializing an associative array:
$people = array(
'Gero' => '0888-257124', ‘Garden' => '0888-3188822');

 Accessing elements by index:


echo $people['Garden']; // 0888-3188822

 Inserting / deleting elements:


$people['Gosho'] = '0237-51713'; // Add 'Gosho'
unset($people['Garden']); // Remove 'Pencho'
print_r($people); // Array([Gero] => 0888-257124 [Gosho] => 0237-51713)

5
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' => 'Gutten tag', 'Bulgaria' => 'Ko staa'];

foreach ($greetings as $key => $value) {


echo "In $key people say \"$value\".";
echo "<br>";
}

6
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  Print the towns in their natural order as
20 object properties
Varna
3
Sofia
["Sofia" => "25","Varna" => "7"]
5
Varna
4
7
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]))
list($town,..)
$sums[$town] = $income;
Assign variables as if
else they were an array
$sums[$town] += $income;
}
print_r($sums);

8
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]++;
} else { isset($array[$i])
$letters[$char] = 1; checks if the key exists
}
}
}
print_r($letters);
9
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
12
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.
13
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

$popularName = “Person";
echo "This is $popularName."; // This is Person.
echo "These are {$popularNames}s."; // These are Persons.

14
Heredoc Syntax
 Heredoc syntax <<<"EOD" .. EOD;

$name = “Hassan";
$str = <<<"EOD"
My name is $name and I am
very, very happy.
EOD;
echo $str;
/*
My name is Hassan and I am
very, very happy.
*/
15
Nowdoc Syntax
 Heredoc syntax <<<'EOD' .. EOD;

$name = “Hassan";
$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.
*/
16

You might also like