0% found this document useful (0 votes)
5 views30 pages

(Lesson x5) Associative Multidimensional Arrays (Halawa)

The document provides an overview of different types of arrays in PHP, including indexed, associative, and multidimensional arrays. It explains how to create, access, modify, and iterate over these arrays, along with examples for each type. Additionally, it discusses built-in functions for handling arrays and demonstrates the use of associative arrays for storing structured data.

Uploaded by

omorsi440
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views30 pages

(Lesson x5) Associative Multidimensional Arrays (Halawa)

The document provides an overview of different types of arrays in PHP, including indexed, associative, and multidimensional arrays. It explains how to create, access, modify, and iterate over these arrays, along with examples for each type. Additionally, it discusses built-in functions for handling arrays and demonstrates the use of associative arrays for storing structured data.

Uploaded by

omorsi440
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Arrays (continued)

Dr mohamed halawa Web Programming (BIS317E)


Types of Arrays
 In PHP, there are different kinds of arrays:
 Indexed arrays - Arrays with a numeric index (previous

lesson)
 Associative arrays - Arrays with named keys

 Multidimensional arrays - Arrays containing one or

more arrays
2. Associative Arrays:
Array with a named key
Associative Array vs. Indexed Array
 Suppose that you want to define an array that stores the
GPAs of five students. Using the indexed array that you
have learned before, it may be declared asind valu
follows:
ex e
$GPA = array(3.7, 2.9, 3, 1.8, 3.9); 0 3.7
or 1 2.9
$GPA = [3.7, 2.9 , 3, 1.8, 3.9]; 2 3
 Such an array can be represented as shown:3  1.8
4 3.9
 You might have wondered that it would have been more
meaningful to use a key/keyword, rather than a numeric
index, to represent each element of the array.
Associative Array vs. Indexed Array
 An associative array is an array that stores multiple values. It
is declared as pairs of “named keys” and “values”.
 Suppose that we want to define this array which stores the
GPAs of five students, using an associative array. There are
two ways of creating/declaring such an associative array:
ke val
$GPA = array("Ola"=>3.7, "Aya"=>2.9, "Ali"=>3 , "Amr"=>1.8 , "Mai"=>3.9);
y ue
Or it can also be written as: Ol 3.7
$GPA["Ola"] = 3.7; a 2.9
$GPA["Aya"] = 2.9; Ay
$GPA["Ali"] = 3; 3
a
$GPA["Amr"] = 1.8; 1.8
Ali
$GPA["Mai"] = 3.9; 3.9
Notes about Associative Arrays
 As no numeric index is used in the associative array, this
implies that the physical locations of the array’s elements
ke val
are unordered. (i.e. each value is located by its key not by y ue
its position within the array). Ola 3.7
 The key used for an associative array shall be unique, as Aya 2.9
each value inside the array is distinguished by its unique
Ali 3
key.
Am 1.8
 You can use any data type for the key/value pairs of the r 3.9
associative array (i.e. integer, string, floating-point, etc.). Mai
In the shown example, a string data type is used for the
key, and a floating-point type is used for the value.
Always remember to put the string values in “quotations”.
Creating Indexed Arrays

// Method 1: Using array() function


$fruits = array("Apple", "Orange", "Banana");
Inde Values
x Apple
// Method 2: Using square bracket shorthand
$fruits = ["Apple", "Orange", "Banana"]; 0 Orange
1 Banana
2
// Method 3: Adding each element of the array separately
$fruits[0] = "Apple";
$fruits[1] = "Orange";
$fruits[2] = "Banana";
Creating Associative Arrays

// Method 1: Creating associative array using array()


function
$person = array("name"=>"John", "age"=>30, "city" => Keys Values
"New York");
// Method 2: Creating associative array using square nam John
bracket shorthand e 30
$person = ["name"=>"John", "age"=>30, "city"=>"New age New York
York"]; city
// Method 3: Creating associative array by adding each
entry separately
$person["name"] ="John";
$person["age"]=30;
$person["city"]="New York";
Accessing Array Elements
Inde Values
x Apple // Accessing elements in an indexed
0 Orange array
1 Banana $fruits = ["Apple", "Orange",
2 "Banana"];
echo $fruits[0];
Keys Values
nam John // Accessing elements in an
e 30
associative array
age $person = ["name"=>"John",
New York "age"=>30, "city"=>"New York"];
city
echo $person["name"];
Modifying Array Elements
Inde Values Inde Values
x // Changing an element x
Apple Apple
$fruits[1] = "Grapes";
0 0 Grapes
Orange
1 // Adding a new element 1 Banana
Banana
$fruits[] = "Pineapple"; 2
2 Pineapple
3
// Changing an element with a specific Key Values
Keys Values key in an associative array s Ali
nam John $person["name"] = "Ali";
e nam 30
30 e
age // Adding an element with a specific key New York
New York in an associative array age
City $person["email"] = john@example.
city com
"[email protected]";
Iterating over Indexed Array via for / foreach

$fruits = ["Apple", "Orange", Output


Inde Values "Banana"];
x for ($i=0; $i<count($fruits); $i+
Apple
0 +)
Orange echo $fruits[$i] . "<br>";
1 Banana $fruits = ["Apple", "Orange",
2 "Banana"];
foreach ($fruits as $v)
echo $v. "<br>";
Iterating over Associative Array via foreach

$person = ["Name"=>"John", "Age"=>30,


"City"=>"New York"];
foreach ($person as $key => $value)
echo "$key <br>";
Keys Values
Name John
$person = ["Name"=>"John", "Age"=>30,
Age 30 "City"=>"New York"];
City New York foreach ($person as $key => $value)
echo "$value <br>";

$person = ["Name"=>"John", "Age"=>30,


"City"=>"New York"];
foreach ($person as $key => $value)
echo "$key is $value <br>";
Indexed Array: Built-in functions
// Sorts an indexed array in ascending order
$fruits = ["Orange", "Apple", "Banana"];
sort($fruits);
foreach($fruits as $v)
Inde Values echo "$v<br>";
x Orange //Checking if an Element Exists
0 Apple if( in_array("Apple", $fruits) )
1 echo "Apple is a fruit";
Banana else
2 echo "Apple is NOT a fruit";
// Remove the last element from the array
array_pop($fruits);
foreach($fruits as $v)
echo "$v<br>";
Associative Array Built-in functions

Keys Values // Sorts an associative array by keys


name John $person = ["Name"=>"John", "Age"=>30,
"City"=>"New York"];
age 30
ksort($person);
city New York foreach ($person as $key => $value)
echo "$key is $value <br>";

Keys Values // Sorts an associative array by values


name John $person = ["Name"=>"John", "Age"=>30,
"City"=>"New York"];
age 30
asort($person);
city New York foreach ($person as $key => $value)
echo "$key is $value <br>";
Removing a specific element
Inde Values
x Apple // Remove a specific element from the indexed
0 Dog array
1 Orange $fruits = ["Apple", "Dog", "Orange", "Banana"];
2 unset($fruits[1]);
Banana foreach($fruits as $v)
3 echo "$v<br>";
Keys Values
name John // Remove a specific element from the associative
array
age 30
$person = ["name"=>"John", "age"=>30,
city New York "city"=>"New York"];
unset($person["age"]);
foreach ($person as $key => $value)
3. Two-Dimensional Array:
Array of arrays
Multi-dimensional Arrays: An overview
 A multidimensional array is an array of arrays!
 Suppose you want to store the marks of four students in
three courses. You might think of storing these marks using
three separate arrays, each of which cours
courscontains four cours
values:
0 25
e1 0 e2
17 0 e3
15
$course1 = [25,20,22,18]; 1 20 1 19 1 17
$course2 = [17,19,23,24]; 2 22 2 23 2 19
$course3 = [15,17,19,21]; 3 18 3 24 3 21
 But this is not the best way to store all these marks. It
would be more practical to store them into one single unit,
with a tabular form (i.e. a matrix of rows and columns).
Multi-dimensional Arrays: An overview
 So, it would be useful to structure and store these marks in
a two-dimensional array with rows and columns, in which
the rows represent the four students, and the columns
represent
0 the1 three
2 courses.
0 25 17 15
1 20 19 17
2 22 23 19
3 18 24 21

 Any element of a two-dimensional array is referenced and


accessed by two indices; the first is the row index, and
Creating a two-dimensional array
 These two indices of a two-dimensional array refer to the
location of an element within that array.
 To declare a two-dimensional array, define the data type
with two square brackets pairs, and assign its multi-values
in a comma-separated list inside curly brackets, like this:
$marks = [ [25,17,15] , [20,19,17] , [22,23,19] , [18,24,21] ];
// 2D Array storing 12 marks (4 students X 3 courses)
0 1 2
 The mark of the first student in the first 0 25 17 15
course is located at mark[0][0] (which is 25). 1 20 19 17
 The mark of the last student in the last 2 22 23 19
course is located at mark[3][2] (which is 21). 3 18 24 21
Multidimensional Array: An array of arrays
Column Index
0 1 2
// Access the elements of a
multidimensional array 0 John Doe 25
$students = [ 1 Jane Smith 30

Row Index
["John", "Doe", 25], 2 Julia Roberts 28
["Jane", "Smith", 30],
["Julia", "Roberts", 28]
]; Output

echo $students[0][1] . "<br>";


echo $students[1][2] . "<br>";
echo $students[2][0] . "<br>";
Looping over two-dimensional indexed array
Column Index
0 1 2
$students = [ $students = [ 0 John Doe 25
["John", "Doe", 25], ["John", "Doe", 25], 1 Jane Smith 30

Row Index
["Jane", "Smith", 30], ["Jane", "Smith", 30], Julia Roberts 28
["Julia", "Roberts", 28] ["Julia", "Roberts", 28] 2
]; ];
Output
foreach ($students as for ($r=0; $r<=2; $r++)
$rowset) {
{ foreach ($c=0;
foreach ($rowset as $c<=2; $c++)
$v) echo
echo "$v "; "$students[$r][$c] ";
Multidimensional Associative Array
Column Key-Index
name position salary
Row 0 John Doe Manager 50000
Inde 1 Jane Smith Developer 60000
x

// Access the elements of a multidimensional associative Output


array
$employees = [
["name" => "John Doe", "position" => "Manager",
"salary" => 50000],
["name" => "Jane Smith", "position" => "Developer",
"salary" => 60000]
];
Looping over two-dimensional associative array
Column Key-Index
name position salary
Row 0 John Doe Manager 50000
Inde 1 Jane Smith Developer 60000 Output
x
// Looping through the multidimensional associative array
$employees = [
["name" => "John Doe", "position" => "Manager", "salary"
=> 50000],
["name" => "Jane Smith", "position" => "Developer",
"salary" => 60000] ];
foreach ($employees as $rowset)
{
foreach ($rowset as $key => $value)
echo "$key: $value <br>";
Multidimensional Associative Array
Column Key-Index
name position salary
24101 John Doe Manager 50000
Row Key- 5
Index Jane Smith Developer 60000
24101
6
// Accesses the name of the second employee Output
$employees = [
"241015" => ["name"=>"John Doe", "position"=>"Manager",
"salary"=>50000],
"241016" => ["name"=>"Jane Smith", "position"=>"Developer",
"salary"=>60000] ];
echo $employees["241016" ]["name"];
Multidimensional Associative Array
Column Key-Index
name position salary
241015 John Doe Manager 50000
Row Key-
241016 Jane Smith Developer 60000
Index
// Adding a new employee
$employees["241017"] = [
"name"=>"Tamer Ali", "position"=>"Analyst", "salary"=>90000 ];

Column Key-Index
name position salary
241015 John Doe Manager 50000
Row Key-Index 241016 Jane Smith Developer 60000
241017 Tamer Ali Analyst 90000
Student information using an associative array
Ke nam grad
ys e e
Alice A-
$students = [ "101" => ["name" => "Alice", "grade" 10 Bob B+
=> "A-"], 1
"102" => ["name" => "Bob", "grade" => 10 Output
"B+"] ]; 2

foreach ($students as $id => $rowset)


{
echo "Student ID: $id<br>";
echo "Name: " . $rowset["name"] . "<br>";
echo "Grade: " . $rowset["grade"] . "<br>";
echo "<br>";
}
Student information using an associative array

Key math scienc englis


$grades = [
s e h
"Alice" => ["math" => 90, "science" => 85, "english" 90 85 88
=> 88], Alic
75 80 70
e
"Bob" => ["math" => 75, "science" => 80, "english" =>
70] ]; Bob
// Calculate and display average grades Output
foreach ($grades as $key => $subjects)
{
$average = array_sum($subjects) / count($subjects);
echo "$key's Average Grade: " .
number_format($average, 2) . "<br>";
}
Non-uniform multidimensional array
different number of columns within each row
Display team lineup by a non-uniform associative
array
$sportsTeam = [ "starters" => [ "point guard" => "John Doe", "shooting guard" =>
"Jane Smith", "small forward" => "Alice Johnson", "power forward" => "Bob Brown",
"center" => "Charlie Davis" ],
"bench" => [ "sub1" => "Tom Wilson", "sub2" => "Emma Taylor", "sub3" =>
echo "Starters:<br>";
"Liam Martin" ] ];
foreach ($sportsTeam["starters"] as $position Output
=> $name)
echo "$position: $name<br>";
echo "<br>Bench:<br>";
foreach ($sportsTeam["bench"] as $sub =>
$name)
Keys point $name<br>";
echo "$sub: shooting small power
center
guard guard forward forward
starte
rs Alice Charlie
John Doe Jane Smith Bob Brown
Johnson Davis
sub3 sub2 sub3
Display a recipe by a non-uniform associative array

name Chocolate Cake


servings 8 Output
egg butt vanil
flour sugar cocoa
s er la
ingredie
nts 2 1.5 1.5 1
$recipe =cup[ "name" => "Chocolate 3 Cake", 1 tsp
cup cup cup
"servings" => 8,
"ingredients" => [ "flour"=>"2 cup", "sugar"=>"1.5 cup",
"cocoa"=>"1.5 cup",
"eggs"=>"3", "butter"=>"1 cup",
"vanilla" => "1 tsp" ] ];
// Display the recipe
echo "<h4>Recipe: " . $recipe["name"] . "</h4>";
echo "<h4>Servings: " . $recipe["servings"] . "</h4>";
echo "<h4>Ingredients:</h4><ul>";
foreach ($recipe["ingredients"] as $item => $amount)

You might also like