Home

Dictionary-Based Collections

An Array as a Dictionary

Introduction

In the above sections, we created arrays and mentioned that each item occupied a specific position with the first item at index 0, the second at index 1, and so on. In reality, what we dit was to ask PHP to automatically assign an index to each list item.

In reality, an array is like a dictionary-based list where each item is in the form key => value. In the above section, we had let the interpreter create a key for each item instead of us doing it manually. The actual item of an array uses the formula key => value. In this case, you must create each key yourself. The value follows the description we have used so far for the items of an array.

The key of an array can be a natural number type or a string. The value can be any type of value, including an array. Each list item uses the formula:

key => value

As seen above, each item (key => value) ends with a comma but you can omit the comma of the last item. As mentioned already, a key can be a number. Here are examples that use integers:

<?php
$semester = array(
    1 => "January",
    2 => "February",
    3 => "March",
    4 => "April",
    5 => "May",
    6 => "June"
);
?>

The keys don't have to be consecutive. Each can have any value you want. Here are examples:

<?php
$paychekFrequencies = array(
    52 => "Weekly",
    12 => "Monthly",
    26 => "Biweekly",
    24 => "Semimonthly",
);
?>

A key can be a string. Here are examples:

$timeWorked = array(
    "Monday" => 8.50,
    "Tuesday" => 6.00,
    "Wednesday" => 8.00,
    "Thursday" => 10.00,
    "Friday" => 9.50,
    "Saturday" => 0,
    "Sunday" => 0
);

Actually, the key has to be compatible or reconciliable with a natural number. For example, the keys can be provided as double-quoted integers. Here are examples:

$semester = array(
    "7"  => "July",
    "8"  => "August",
    "9"  => "September",
    "10" => "October",
    "11" => "November",
    "12" => "December",
);

In this case, each key would be converted to its integer equivalent. Other rules are as follows:

  • If the key is a floating-point number, it would be truncated to the closest integer
  • If the key is a Boolean value, the true value would be converted to 1 and false would be converted to 0

As mentioned in the introductory sections, the keys of an array can be of different types. Here are examples:

$timeZones = array(
    "PST"  => "Pacific Standard Time",
    "MST"  => "Mountain Standard Time",
    "CST"  => "Central Standard Time",
    "EST"  => "Eastern Standard Time",
    "AST"  => "Atlantic Standard Time",
    "AKST" => "Alaskan Standard Time",
    "HST"  => "Hawaii-Aleutian Standard Time",
    -11    => "Samoa standard time",
    10     => "Chamorro Standard Time"
);

You can provide a key for only one item. Here is an example where only the key of the first item is provided:

<?php
$metroLine = array(
    1 => "Shady Grove",
         "Rockville",
         "Twinbrook",
         "White Flint",
         "Grosvenor-Strathmore",
);
?>

If you do this, each subsequent item would receive a numeric key that is the increment from the key you provided. In this case, the item for the "Rockville" value would receive a key of 2. The key for "Twinbrook" would be 3. "White Flint" would have a key of 4 and "Grosvenor-Strathmore" would have key = 5. In the same way, you can provide a key for an item somewhere inside the list and omit a key for the other items. Here is an example:

$metroLine = array(
         "Vienna",
         "Dunn Loring",
         "West Falls Church",
    5 => "Virgina Sq-GMU",
         "Clarendon",
         "Court House",
);

In this case, the first item receives an index of 0. The second item receives an index of 1, and so on, up to the first item that received an explicit index. Start from there, the items after that will receive incrementing numbers as index. So in this case, "Vienna" has an index 0, "Dunn Loring" has an index of 1, "West Falls Church" has an index of 2, "Virgina Sq-GMU" had received an explicit index of 5, "Clarendon" receives a subsequent index of 6, and "Court House" has an index of 7. You can also also assign indexes to different items inside the array. Here are examples:

$metroLine = array(
          "Vienna",
          "Dunn Loring",
          "West Falls Church",
    5 =>  "Virginia Sq-GMU",
          "Clarendon",
          "Court House",
    10 => "Farragut West",
          "McPherson Square",
          "Metro Center",
          "Federal Triangle"       
);

Accessing an Item

The formula to access the value of an item of an array is:

$variable-name[key]

Once you provide the key in the square brackets, the variable provides the value. Here are examples:

<?php
$censusBureauRegions = array(
    1 => "New England",
    2 => "Mid-Atlantic",
    3 => "East North Central",
    4 => "West North Central",
    5 => "South Atlantic",
    6 => "East South Central",
    7 => "West South Central",
    8 => "Mountain",
    9 => "Pacific"
);

echo "<h3>Census Bureau Regions</h3>";
echo "<pre>---------------------------------</pre>";
echo "Division 1: " . $censusBureauRegions[1] . "<br>";
echo "Division 2: " . $censusBureauRegions[2] . "<br>";
echo "Division 3: " . $censusBureauRegions[3] . "<br>";
echo "Division 4: " . $censusBureauRegions[4] . "<br>";
echo "Division 5: " . $censusBureauRegions[5] . "<br>";
echo "Division 6: " . $censusBureauRegions[6] . "<br>";
echo "Division 7: " . $censusBureauRegions[7] . "<br>";
echo "Division 8: " . $censusBureauRegions[8] . "<br>";
echo "Division 9: " . $censusBureauRegions[9]
?>

This would produce:

Accessing a List Item

Remember that you can use curly brackets instead of square brackets to access an item. In both cases, remember to provide the right key when  accessing an item. Here are examples:

<?php
$paychekFrequencies = array(
    52 => "Weekly",
    12 => "Monthly",
    26 => "Biweekly",
    24 => "Semimonthly",
);

echo "<h3>Payroll Frequencies</h3>";
echo "<pre>---------------------</pre>";
echo $paychekFrequencies{26} . "<br>";
echo $paychekFrequencies{12} . "<br>";
echo $paychekFrequencies{52} . "<br>";
echo $paychekFrequencies{24}
?>

This would produce:

An Array as a Dictionary

If you had explicitly provided indexes to some items and not to others, you should keep that in mind when accessing the items. Here is an example:

<?php
$metroLine = array(
         "Vienna",
         "Dunn Loring",
         "West Falls Church",
    5 => "Virginia Sq-GMU",
         "Clarendon",
         "Court House",
);

echo "<h3>Metro System: Red Line</h3>";
echo "<pre>----------------------------</pre>";
echo "Station Name: " . $metroLine{0} . "<br>";
echo "Station Name: " . $metroLine{1} . "<br>";
echo "Station Name: " . $metroLine{2} . "<br>";
echo "Station Name: " . $metroLine{5} . "<br>";
echo "Station Name: " . $metroLine{6} . "<br>";
echo "Station Name: " . $metroLine{7}
?>

This would produce:

Accessing a List Item

Here is another example:

<?php
$metroLine = array(
          "Vienna",
          "Dunn Loring",
          "West Falls Church",
    5 =>  "Virginia Sq-GMU",
          "Clarendon",
          "Court House",
    10 => "Farragut West",
          "McPherson Square",
          "Metro Center",
          "Federal Triangle"
         
);

echo "<h3>Metro System: Red Line</h3>";
echo "<pre>---------------------</pre>";
echo "Station Name: " . $metroLine{0} . "<br>";
echo "Station Name: " . $metroLine{1} . "<br>";
echo "Station Name: " . $metroLine{2} . "<br>";
echo "Station Name: " . $metroLine{5} . "<br>";
echo "Station Name: " . $metroLine{6} . "<br>";
echo "Station Name: " . $metroLine{7} . "<br>";
echo "Station Name: " . $metroLine{10} . "<br>";
echo "Station Name: " . $metroLine{11} . "<br>";
echo "Station Name: " . $metroLine{12}. "<br>";
echo "Station Name: " . $metroLine{13}
?>

This would produce:

Accessing a List Item

The number-based keys can be provided in regular numbers or as strings. Here are two examples:

<?php
$timeZones = array(
    "PST"  => "Pacific Standard Time",
    "MST"  => "Mountain Standard Time",
    "CST"  => "Central Standard Time",
    "EST"  => "Eastern Standard Time",
    "AST"  => "Atlantic Standard Time",
    "AKST" => "Alaskan Standard Time",
    "HST"  => "Hawaii-Aleutian Standard Time",
    -11    => "Samoa standard time",
    10     => "Chamorro Standard Time"
);

echo "<h3>US Time Zones</h3>";
echo "<pre>-----------------------------<br>";
echo $timeZones["PST"] . "<br>";
echo $timeZones["MST"] . "<br>";
echo $timeZones["CST"] . "<br>";
echo $timeZones["EST"] . "<br>";
echo $timeZones["AST"] . "<br>";
echo $timeZones["AKST"] . "<br>";
echo $timeZones["HST"] . "<br>";
echo $timeZones[-11] . "<br>";
echo $timeZones["10"] . "<br>";
echo "-----------------------------</pre>";
?>

This would produce:

Accessing a List Item

Just as mentioned earlier, once you have access to the value of an item, you can use it in an expression or an operation. Here are examples:

<?php
$timesheet = array(
    "EmployeeNumber" => 208416,
    "FirstName" => "Hermine",
    "LastName" => "Ngaleu",
    "HourlySalary" => 25.05,
    "TimeWorked" => 44.00, 
    "EmploymentStatus" => 1
);
$status = array("Part-Time", "Full-Time");

$employeeName = $timesheet["LastName"] . ", " . $timesheet["FirstName"];
$weeklySalary = $timesheet["HourlySalary"] * $timesheet["TimeWorked"];
 
echo "<h3>Employee Record</h3>";
echo "<pre>----------------------------------<br>";
echo "Employee #:        " . $timesheet["EmployeeNumber"] . "<br>";
echo "Employee Name:     " . $employeeName . "<br>";
echo "Employment Status: " . $status[$timesheet["EmploymentStatus"]] . "<br>";
echo "Hourly Salary:     " . $timesheet["HourlySalary"] . "<br>";
echo "Time Worked:       " . $timesheet["TimeWorked"] . "<br>";
echo "Weekly Salary:     " . $weeklySalary . "<br>";
echo "===================================</pre>";
?>

This would produce:

Accessing a List Item

 
 
 

Operations on Items

Changing the Value of an Item

To change the value of an item, access it by its index and assign the desired value. Here are examples:

<?php
$timesheet = array(
    "EmployeeNumber" => 208416,
    "FirstName" => "Hermine",
    "LastName" => "Ngaleu",
    "HourlySalary" => 25.05,
    "TimeWorked" => 44.00, 
    "EmploymentStatus" => 1
);

$timesheet["HourlySalary"] = 25.65
?>

For Each Key

You can access each item of a dictionary-based collection using their keys. Normally, if you create a list where the keys were automatically created by the PHP interpreter, you can access each item using a foreach operator. Here is an example:

<?php
$elements = array("Hydrogen", "Helium", "Lithium", "Beryllium",
                  "Boron", "Carbon", "Nitrogen", "Oxygen",
                  "Fluorine", "Neon", "Sodium", "Magnesium"
);

echo "<h2>Chemical Elements</h2>";

echo "<table border='2'>
       <tr>
         <td><b>Element</b></td>
       </tr>";

foreach($elements as $number => $atom)
{
    echo "<tr><td>" . $atom . "</td></tr>";
}
echo "</table";
?>

This would produce:

For Each Key

In this case, you don't use and don't care about the key of each item. If you have a dictionary-based collection, you may need to access the key of each item. In reality, every PHP array or list created as an array is a dictionary-based collection. The difference is that, with classic arrays or regular lists, you let the keys be automatically generated, but with a dictionary-based collection, you specify the keys yourself.l

Whenever you create a classic array or a regular list, the PHP interpreter generates a 0-based index for each item. Regardless of how you create your collection, PHP provides a mechanism to access the key of each item. This is done using the second formula of the foreach loop. It is available as follows:

foreach(list-name as $key-name => $variable-name)
    statement

In the parentheses, specify a name for the common key, followed by =>. In the statement, you can access the $key-name. At a minimum, you can display its value. Here is an example:

<?php
$layers = array("Inner Core", "Outer Core", "Mantle", "Crust");

echo "<h2>Earth Layers</h2>";

echo "<table border='2'>
       <tr>
         <td><b>Position</b></td>
         <td><b>Layer</b></td>
       </tr>";

foreach($layers as $position => $layer)
{
    echo "<tr><td style='text-align: center;'>" . $position . "</td><td>" . 
         $layer . "</td></tr>";
}
echo "</table";
?>

This would produce:

For Each Key

If you had created the keys yourself, the $key-name allows you to access every one of them. Here is an example:

<?php
$australia = array(
    "WA"  => "Western Australia",
    "NT"  => "Northern Territory",
    "SA"  => "South Australia",
    "QLD" => "Queensland",
    "NSW" => "New South Wales",
    "VIC" => "Victoria"
);

echo "<h2>Australia: States</h2>";

echo "<table border='2'>
       <tr>
         <td><b>Code</b></td>
         <td><b>State</b></td>
       </tr>";

foreach($australia as $code => $state)
{
    echo "<tr><td style='text-align: center;'>" . $code . "</td><td>" . 
         $state . "</td></tr>";
}
echo "</table";
?>

This would produce:

For Each Key

If some keys were manually created and not some others, the $key-name of the foreach operator will recognize the named keys and the automatically generated ones.

Because the foreach operator of a dictionary-based collection allows you to access each key, you can use it in an expression for any operation you want. For example, you can get a key from a user and find the corresponding item in the collection, or you can find out whether an item based on the provided key exists, or you can find out if a supplied value matches a key in the collection. Here is an example:

login1.php

<!DOCTYPE html>
<html>
<head>
<title>Employee Login</title>
<style type="text/css">

#formulation
{
    margin: auto;
    width:  250pt;
}
#main-title
{
    font-size:   18pt;
    font-weight: bold;
    font-family: Georgia, "Times New Roman", Times, serif;
}
</style>
</head>
<body>

<?php
echo "<form name='frmTimeSheet' action='login2.php' method='post'>
      <div id='formulation'>
      <p id='main-title'>Employee Login</p>

      <table>
        <tr>
          <td>Username:</td>
          <td>
	    <input name='txtUsername' type='text'></input></td>
        </tr>
        <tr>
          <td>Password:</td>
          <td>
	    <input name='txtPassword' type='password'></input>
          </td>
        </tr>
        <tr>
          <td>&nbsp;</td>
          <td style='text-align: center;'>
	    <input name='Submit' type='submit' value='Submit'></input>
          </td>
        </tr>
      </table>
    </div>
    </form>";
?>
</body>
</html>

login2.php

<!DOCTYPE html>
<html>
<head>
<title>Employee Login</title>
<style type="text/css">

#formulation
{
    margin: auto;
    width:  250pt;
}
#main-title
{
    font-size:   18pt;
    font-weight: bold;
    font-family: Georgia, "Times New Roman", Times, serif;
}
</style>
</head>
<body>
<div id="formulation">
<p id='main-title'>Employee Time Sheet</p>

<?php
$employees = array("fswanson" => "P@s\$W0rd1",
                   "cdobson"  => "P@s\$w0rd2",
                   "ngrants"  => "p@\$sW0rD3",
                   "anoumsi"  => "p@\$Sw0Rd4",
                   "hngaleu"  => "P@S\$w0rD5");

$success = false;
$username = htmlspecialchars($_POST['txtUsername']);
$password = htmlspecialchars($_POST['txtPassword']);

foreach($employees as $user => $pass){
    if(($user == $username) and ($pass == $password)){
        $success = true;
    }
}
?>

<?php if($success == true): ?>
<p>Successful Login</p>
<?php else: ?>
<p>Invalid Login!!!</p>
<?php endif ?>
</div>
</body>
</html>

This would produce:

For Each Key

For Each Key

For Each Key

For Each Key

Because the key holds a value, you can perform any appropriate operation you want on it. Here is an example:

<?php
$elements = array("Hydrogen", "Helium", "Lithium", "Beryllium",
                  "Boron", "Carbon", "Nitrogen", "Oxygen",
                  "Fluorine", "Neon", "Sodium", "Magnesium"
);

echo "<h2>Chemical Elements</h2>";

echo "<table border='2'>
       <tr>
         <td><b>Atomic #</b></td>
         <td><b>Element</b></td>
       </tr>";

foreach($elements as $number => $atom)
{
    echo "<tr><td style='text-align: center;'>" . ($number + 1) . "</td><td>" . 
                      $atom . "</td></tr>";
}
echo "</table";
?>

This would produce:

For Each Key

An Array as an Item

As mentioned for automatic indexes, an array can contain another array. To create the internal array, you have many options. You can give it a named index, followed by => array(). In the parentheses, define the items, each with its own named index and its value. Here is an example:

<?php
$timesheet = array(
    "EmployeeNumber" => 208416,
    "FirstName"      => "Hermine",
    "LastName"       => "Ngaleu",
    "HourlySalary"   => 25.05,
    "time" => array(
        "Monday" => 8.50,
        "Tuesday" => 6.00,
        "Wednesday" => 8.50,
        "Thursday" => 8.00,
        "Friday" => 9.50,), 
    "EmploymentStatus" => 1);
?>

To access an item of the internal array, use its name in {} or [] applied to the array variable, followed by the index of the item in its own {} or []. Here is an example:

<?php
$timesheet = array(
    "EmployeeNumber" => 208416,
    "FirstName"      => "Hermine",
    "LastName"       => "Ngaleu",
    "HourlySalary"   => 25.05,
    "time" => array(
        "Monday" => 8.50,
        "Tuesday" => 6.00,
        "Wednesday" => 8.50,
        "Thursday" => 8.00,
        "Friday" => 9.50,), 
    "EmploymentStatus" => 1);

    $timeWorked = $timesheet{"time"}{"Monday"} + $timesheet{"time"}{"Tuesday"} + 
                  $timesheet{"time"}{"Wednesday"} +
                  $timesheet{"time"}{"Thursday"} + $timesheet{"time"}{"Friday"};
    $weeklySalary = $timesheet["HourlySalary"] * $timeWorked;

echo "<h3>Employee Record</h3>";
echo "<pre>=================================<br>";
echo "Employee #:        " . $timesheet["EmployeeNumber"] . "<br>";
echo "First Name:        " . $timesheet["FirstName"] . "<br>";
echo "Last Name:         " . $timesheet["LastName"] . "<br>";
echo "Hourly Salary:     " . $timesheet["HourlySalary"] . "<br>";
echo "Employment Status: " . $timesheet["EmploymentStatus"] . "<br>";
echo "--------------------------------<br>";
echo "Time Worked        " . "<br>";
echo "Monday:            " . $timesheet{"time"}["Monday"] . "<br>";
echo "Tuesday:           " . $timesheet{"time"}{"Tuesday"} . "<br>";
echo "Wednesday:         " . $timesheet{"time"}["Wednesday"] . "<br>";
echo "Thursday:          " . $timesheet{"time"}["Thursday"] . "<br>";
echo "Friday:            " . $timesheet{"time"}{"Friday"} . "<br>";
echo "--------------------------------<br>";
echo "Weekly Time:       " . $timeWorked  . "<br>";
echo "Weekly Salary:     " . $weeklySalary . "<br>";
echo "=================================</pre>";
echo "</pre>"
?>

This would produce:

Accessing a List Item

As an alternative, the internal array can be created like an array variable. Each one of its items can have its own named key. Here is an example:

 <?php
$timesheet = array(
    "EmployeeNumber" => 208416,
    "FirstName"      => "Hermine",
    "LastName"       => "Ngaleu",
    "HourlySalary"   => 24.45,
    $work = array(
        "Monday" => 8.50,
        "Tuesday" => 6.00,
        "Wednesday" => 8.50,
        "Thursday" => 8.00,
        "Friday" => 9.50,), 
    "EmploymentStatus" => 1);
?>

To access an item of the internal array, you can use the name of that array and apply {} or [] to it. In the brackets, enter the named index of the item. Here are examples:

 <?php
$timesheet = array(
    "EmployeeNumber" => 208416,
    "FirstName"      => "Hermine",
    "LastName"       => "Ngaleu",
    "HourlySalary"   => 24.45,
    $work = array(
        "Monday" => 8.50,
        "Tuesday" => 6.00,
        "Wednesday" => 8.50,
        "Thursday" => 8.00,
        "Friday" => 9.50,), 
    "EmploymentStatus" => 1);

    $timeWorked = $work{"Monday"} + $work{"Tuesday"} + $work{"Wednesday"} +
                  $work{"Thursday"} + $work{"Friday"};

echo "<h3>Employee Record</h3>";
echo "<pre>--------------------------------<br>";
echo "Employee #:        " . $timesheet["EmployeeNumber"] . "<br>";
echo "First Name:        " . $timesheet["FirstName"] . "<br>";
echo "Last Name:         " . $timesheet["LastName"] . "<br>";
echo "Hourly Salary:     " . $timesheet["HourlySalary"] . "<br>";
echo "Employment Status: " . $timesheet["EmploymentStatus"] . "<br>";
echo "--------------------------------<br>";
echo "Time Worked        " . "<br>";
echo "Monday:            " . $work["Monday"] . "<br>";
echo "Tuesday:           " . $work{"Tuesday"} . "<br>";
echo "Wednesday:         " . $work["Wednesday"] . "<br>";
echo "Thursday:          " . $work{"Thursday"] . "<br>";
echo "Friday:            " . $work{"Friday"} . "<br>";
echo "--------------------------------<br>";
echo "Weekly Time:       " . $timeWorked  . "<br>";
echo "</pre>"
?>

This would produce:

The Value of an Item

In the same way, you can create as many internal arrays as you want.

 
   
 

Previous Copyright © 2015, FunctionX Next