(Lesson x5) Associative Multidimensional Arrays (Halawa)
(Lesson x5) Associative Multidimensional Arrays (Halawa)
lesson)
Associative arrays - Arrays with named keys
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
Row Index
["John", "Doe", 25], 2 Julia Roberts 28
["Jane", "Smith", 30],
["Julia", "Roberts", 28]
]; Output
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
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