Professional Documents
Culture Documents
Associative Arrays
Associative Arrays
Associative Arrays (Maps, Dictionaries)
Associative arrays are arrays indexed by keys
Not by the numbers 0, 1, 2, 3, …
$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"; //
5
Iterating Through Associative Arrays
foreach ($array as $key => $value)
Iterates through each of the key-value pairs in the array
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;
?>
$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