Task Twelve - Menu - PHP Tutorial

This example implements a menu. It introduces the switch statement (this is a compact way of replacing multiple if statements). The program contains an array with five elements. You can add and delete array items. You can browse the data by selecting the next or prevoius items in the array. To quit, press 'q'.

Here is a slightly simplified Jackson Structure Diagram of the program.

Here is a screen shot of the program.

Here is the program code.


<?php

function menu()
{
  echo "\n\n";
  echo "========\n";
  echo "= MENU =\n";
  echo "========\n";
  echo "\n";
  echo "Next record ........ n\n";
  echo "Previous record .... p\n";
  echo "Add ................ a\n";
  echo "Delete ............. d\n";
  echo "\n";
  echo "Quit ............... q\n";
  echo "\n";
  echo "Make your choice ... ";

  $choice = trim(fgets(STDIN));

  return $choice;
}

// -----------------------------------------------------------------
// ----- MAIN PROGRAM ----------------------------------------------
// -----------------------------------------------------------------

set_time_limit(0);     // Allow the program an umlimited run time
                       // By default programs time out after 30 seconds
                       // 0 gives an unlimited run time
                       // This time is measured in seconds

define("numRec", 5);   // Define the number of records as a constant

// Initialise the array data
// Create an array containing five text strings
// Use a for loop that iterates from 0 to 4
for ($ii = 0; $ii < numRec; $ii++)
{
  $record[] = "Empty"; // Add a string to next free array location
}

// Clear the screen
echo "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";

// The main program loop
do
{
  $key  = key($record);       // Find out which array item is current
  $item = current($record);   // Get the value of the current item
  
  // Display the current position and data held at that position
  echo "\n\nRecord Number ... $key. Record Data ... $item\n\n";

  $menu_choice = menu();      // Display and get the menu choice

  // Decide what action to take based on the value in $menu_choice
  switch ($menu_choice)
  {
    // NEXT RECORD
    case 'n' : 
      if ($key < numRec - 1)  // Prevent falling off the end of the array
      {
        next($record);        // Make the next array position current
      }
      break;

    // PREVIOUS RECORD 
    case 'p' : 
      if ($key > 0)           // Prevent falling off the end of the array
      {
        prev($record);        // Make the previous array position current
      }	
      break;

    // ADD A RECORD
    case 'a' : 
      echo "\n\nPlease enter some text to be stored in the array ... ";
      $record[$key] = fgets(STDIN);
      break;

    // CLEAR A RECORD
    case 'd' : 
      $record[$key] = "";
      break;

    // QUIT
    case 'q' :
      break;     // Accept 'q' as a valid case but take no action

    // DISPLAY AN ERROR MESSAGE
    default:
      echo "\n\nInvalid menu choice.";
  }
  
  echo "\n\n\n\n\n\n";
}
while ($menu_choice <> 'q');

// -----------------------------------------------------------------

?>

 

Code

Explanation

set_time_limit(0);

By default, php programs time out after 30 seconds. If you write a proram with an infilite loop (will never end), php will kill it after 30 seconds. This program is interactive and needs longer than a 30 second run time. This line of code provides an unlimited run time.

define("numRec", 5);

This defines numRec as a constant. Note that it is numRec and not $numRec. Constants are useful because they can not be accidentaly changed while the program is running. A constant is defined once at the start of the program and used many times in the program code. In this program you can change numRec from 5 to 100 and your program will immediately work with 100 records instead of 5. No other changes are needed in the program. This is useful and efficient.

for ($ii = 0; $ii < numRec; $ii++)
{
  $record[] = "Empty";
}

This is a for loop that repeats numRec times. (If the numRec constant is changed the loop still repeats the correct number of times).

On each repetition of the loop, "Empty" is added to the next free position of the $record[] array.

do {}
{
  // Repeat this block of
  // code as long as 'q' was
  // not selected.
}
while ($menu_choice <> 'q');

A do loop used to repeat the program code until the user selects 'q' to quit.

$key  = key($record);
$item = current($record);

PHP has a number of useful array functions and properties built in.

PHP keeps a pointer to the current array position. The key function returns this position.

The current function returns the data at the current position.

$menu_choice = menu();

The menu function displays the menu choices and returns the user's choice.

switch ($menu_choice)
{
  // Select a case depending
  // on the value held
  // in $menu_choice
}

The switch statement is a convenient shorthand used to replace multiple if, then, else ststements.

If there is a matching case, that code is run all the way to the end of the switch statement or as far as the first break statement.

If none of the cases match, the optional default statement code is run.

// NEXT RECORD
case 'n' :
  if ($key < numRec - 1)
  {
    next($record);
  }
  break;

if $menu_choice contained 'n', this case will match.

The next record will be selected unless the last record is already selected. This is achieved by using the built-in next function.

This function is only called if $key is less that the numRec constant.

The break statement is important. If this is missing, all the code up to the end of the switch statement will run. This will have undesireable effects.

// DISPLAY AN ERROR MESSAGE default:
  echo "\n\nInvalid menu choice.";

This code will run if none of the previous cases matched.

 

Learning Tasks

  • Add stub (non working) choices to the menu to provide save and load choices.
  • Note: The code needed for these choices is in the next example.
  • The word "Save" or "Load" should be displayed to show that your menu choices are working.