Richland College Multimedia Learning Center

Digital Media Programming with PHP and MySQL
Updated 3/2/2020 at 8:50pm

More Arrays, Strings, and Session Variables

Associative Arrays

PHP allows you to create other kinds of arrays in addition to the ones that you have already seen. One other kind of array in PHP is the associative array.

The indices in an associative array are strings.

Consider an array that stores the names of capital cities for some states. You could, of course, use a normal array to store the city names. But it would be difficult to keep track of the relationship between the state (name) and the city name in a normal array. What if you could use the state name as the index of the array? Well, you can do this with an associative array!

This Capital Cities page demonstrates the basics of using an associative array. Actually, the page has two associative arrays, and shows you two different ways to create an associative array. The first array is for states, and the second array is for countries of the world.

The code for the Capital Cities page is shown below. This is file assoc.php:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <link type="text/css" rel="stylesheet" href="PHPstyles.css">
  <title>Associative array demo</title>
</head>

<body>
  <div id="mainDiv">
    <h1>Associative Array Demo</h1>

    <?php
    $stateCap["Alaska"] = "Juneau";
    $stateCap["Indiana"] = "Indianapolis";
    $stateCap["Michigan"] = "Lansing";

    if (array_key_exists("Alaska", $stateCap))
    {
      print "Alaska: ";
      print $stateCap["Alaska"];
      print "<br /><br />";
    }

    $worldCap = array(
      "Albania"=>"Tirana",
      "Japan"=>"Tokyo",
      "United States"=>"Washington DC"
      );

    if (array_key_exists("Japan", $worldCap))
    {
      print "Japan: ";
      print $worldCap["Japan"];
      print "<br /><br />";
    }

    foreach ($worldCap as $country => $capital){
      print "$country: $capital<br />\n";
    } // end foreach

    ?>
  </div>
</body>
</html>

Please note these points about the above code:

By the way, an associative array is used automatically by PHP to store the information that comes into a PHP page from an HTML form. The name of each of the form's elements is the index, and the value in each element is, of course, the value of the array element. If the form's method attribute is "post", the associative array in the form's action page is the familiar variable $_POST, which you have seen before. See the next section for more information.


foreach Loops

We saw for loops in the previous handout. The present handout will start off by explaining an even handier kind of loop for handling arrays: The foreach loop.

This Array Key page shows a regular for loop for review, and then demonstrates the basics of using a foreach loop.

The code for the Array Key page is shown below. This is file ArrayKey.php:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <link type="text/css" rel="stylesheet" href="PHPstyles.css">
  <title>Some Loops</title>
</head>

<body>
  <div id="mainDiv">
    <h1>Some Loops</h1>

    <?php

    $numbers = array(125, 256, 1047, -354, 2, 0, 10000);
    $greekLetters = array("letterOne" => "alpha", "letterTwo" => "beta", "letterThree" => "gamma", "letterFour" => "delta", 
	    "letterFive" => "epsilon");
    print "<h3>A Regular for loop:</h3>\n";
    print "<ul>\n";
	for ($i = 0; $i < count($numbers); $i++)
	{
	  print "  <li>The index is " . $i . " and the value is " . $numbers[$i] . "</li>\n";
	}
    print "</ul>\n";
	
    print "<h3>A foreach loop:</h3>\n";
    print "<ul>\n";
    foreach ($greekLetters as $letterOrder => $letterValue){
	  print "  <li>The key is " . $letterOrder . " and the value is " . $letterValue . "</li>\n";
    } // end foreach loop
    print "</ul>\n";

    ?>
  </div>
</body>
</html>

Please note these points about the above code:


Built-in Associative Arrays

PHP automatically creates some associative arrays when your page loads into the PHP server (and is eventually sent as an HTML page to your browser). Some of these associative arrays are:

This Form Reader page demonstrates one very handy way to read the information that comes into your PHP page from an HTML form.

The code for the HTML form page is shown below. This is file sampleForm.html:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <link type="text/css" rel="stylesheet" href="PHPstyles.css">
  <title>Sample Form</title>
</head>
<body>
  <div id="mainDiv">
    <h1>Sample form</h1>
    <form action="formReader.php" method="post">
    <table>
    <tr>
      <td>Name</td>
      <td>
        <input type = "text"
               name = "name" />
      </td>
    </tr>

    <tr>
      <td>Email</td>
      <td>
        <input type = "text"
               name = "email" />
      </td>
    </tr>

    <tr>
      <td>Phone</td>
      <td>
        <input type = "text"
               name = "phone" />
      </td>
    </tr>

    <tr>
      <td colspan="2">
        <input type = "submit"
               value = "Send the Form Data" />
      </td>
    </tr>
    </table>
    </form>
  </div>
</body>
</html>

The code for the Form Reader page is shown below. This is file formReader.php:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <link type="text/css" rel="stylesheet" href="PHPstyles.css">
  <title>Form Reader</title>
</head>
<body>
  <div id="mainDiv">
    <h1>Form Reader</h1>
    <h3>Here are the fields I found in the $_REQUEST array:</h3>
    <?php
    print <<<HERE
    <table>
    <tr>
      <th>Field</th>
      <th>Value</th>
    </tr>
HERE;

    foreach ($_REQUEST as $field => $value){
      print <<<HERE
      <tr>
        <td>$field</td>
        <td>$value</td>
      </tr>
HERE;
    } // end foreach
    print "</table>\n";

    ?>
  </div>
</body>
</html>

Please note these points about the above code:


String Functions

PHP has a large number of string manipulation functions built in.

This Pig Latin page demonstrates how to use some of these built-in string functions.

The code for the Pig Latin page is shown below. This is file pigify.php:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <link type="text/css" rel="stylesheet" href="PHPstyles.css">
  <title>Pig Latin Generator</title>
</head>
<body>
  <div id="mainDiv">
    <h1>Pig Latin Generator</h1>
    <?php
    if (!isset($_POST["inputString"]) || $_POST["inputString"] == ""){
      print <<<HERE
      <form action="pigify.php" method="post">
      <textarea name = "inputString"
                rows = "20"
                cols = "40"></textarea>
       <input type = "submit"
              value = "pigify" />
       </form>
       
HERE;
    } else {
      //there is a value, so we'll deal with it
      $inputString = $_POST["inputString"];
      //break phrase into array
      $words = explode(" ", $inputString);
      $newPhrase = "";
      foreach ($words as $theWord)
      {
        $theWord = rtrim($theWord);
        if ($theWord != "")
        {
          $firstLetter = substr($theWord, 0, 1);
          $restOfWord = substr($theWord, 1, strlen($theWord)-1);
          //print "$firstLetter) $restOfWord  \n";
          if (strstr("AEIOU", strtoupper($firstLetter)))
          {
            //it's a vowel
            $newWord = $theWord . "way";
          }
          else
          {
            //it's a consonant
            $newWord = $restOfWord . $firstLetter . "ay";
          } // end if
          $newPhrase = $newPhrase . $newWord . " ";
        }
      } // end foreach
      print $newPhrase;

    } // end if
      
    ?>
  </div>
</body>
</html>

Please note these points about the above code:


Session Variables

Session variables can be used to store information between page loads during the current user session (while their browser is still open).

Session variables are stored in the $_SESSION associative array. This array is stored in the PHP server's memory, so it retains its values even after a PHP page has been loaded and/or closed.

In the following sample code, we will use a session variable to keep unwanted visitors out of our site's main index page.

You can see what happens if you go to the index page without logging in, here. Briefly, what happens is that you are redirected to a "login" form page. (When you are ready to try logging in, the username is nosmo and the password is king)

First, here is the page which we are protecting from unwanted access. It is index.php:

<?php
  session_start();
  if (!isset($_SESSION["fakeLogin"]) || $_SESSION["fakeLogin"] != "success")
  {
    $filename = "PHPStuff/Sessions/fakeLogin.php";
    header("Location: http://" .$_SERVER['HTTP_HOST']. "/" . $filename);
  }
?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Main Index Page</title>
  <link rel="stylesheet" type="text/css" href="../PHPstyles.css" />
</head>

<body>
  <div id="mainDiv">
    <h3>
      This is the Fake Web Site's index page.
    </h3>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur accumsan 
      lacus vitae mi consequat, quis auctor lacus maximus. Nulla dolor magna, 
      elementum ut interdum eget, venenatis a quam. Proin vel purus gravida, 
      consequat quam eu, interdum risus. Ut bibendum sagittis suscipit. Sed 
      eleifend ullamcorper diam vel varius. Etiam luctus, erat.
    </p>
    <a href="fakeUnset.php">Log Out</a>
  </div>
</body>
</html>

Now, here is the HTML form page that you are redirected to: This is page fakeLogin.php:

<?php
  session_start();
?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="../PHPstyles.css" />
  <title>Fake Login Page</title>
  <script type="text/javascript">
  	function positionCursor()
  	{
  		document.getElementById("username").focus();
  	}
  </script>
</head>

<body onload="positionCursor();">
  <div id="mainDiv">
    <?php
      if (isset($_SESSION["fakeLogin"]) && $_SESSION["fakeLogin"] == "error")
      {
        echo '<h3>You entered invalid login credentials.  Please try again.</h3>';
      }
    ?>
    <form name="theForm" action="fakeLoginAction.php"
          method="post">
      Please enter your login/user name:
      <input type="text" name="username" id="username" />
      <br />
      <br />
      Please enter your password:
      <input type="password" name="thepwd" id="thepwd" />
      <br />
      <br />
      <input type="submit" value="Log In" />
    </form>
  </div>
</body>
</html>

The login action page is fakeLoginAction.php:

<?php
session_start();
// In the real world, the password would be looked up in a database.
// If the password is correct, the session variable would be set.
// If the password is incorrect, the user would be redirected back
//   to the login form page.
// For this fake login demo, the username is "nosmo" and the password is "king".

$username = $_POST["username"];
$password = $_POST["thepwd"];

if ($username == "nosmo" && strcmp($password,"king") == 0)
{
  $_SESSION["fakeLogin"] = "success";
  $filename = "PHPStuff/Sessions/index.php";
  header("Location: http://" .$_SERVER['HTTP_HOST']. "/" . $filename);
}
else
{
	$_SESSION["fakeLogin"] = "error";
  $filename = "PHPStuff/Sessions/fakeLogin.php";
  header("Location: http://" .$_SERVER['HTTP_HOST']. "/" . $filename);
}
?>

If you look back at the code for the index page, you will see that there is a "Log Out" link on it. If you click that link, the page which unsets (resets) the session variable is fakeUnset.php. Here is that page:

<?php
session_start();
// Use this page to unset the fake session variable which is used for fakeLogin.php
error_reporting(-1);
unset($_SESSION["fakeLogin"]);

?>

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="../PHPstyles.css" />
  <title>Fake Login Reset/Unset</title>
</head>

<body>
  <div id="mainDiv">
	  <h3>The fake session variable has been reset/unset</h3>
	  <a href="index.php">Display the index page again</a>
	</div>
</body>
</html>

Please note these points about the above code:

ADDITIONAL NOTE: For future use, if you have any PHP code after the call to header() for a redirect to another page, you should call exit() after the call to header(). The exit() function tells the PHP processor to stop processing the PHP code in your page. If you don't call exit(), the PHP processor will continue to process your PHP code that is after the call to header(), and you may experience unexpected results.