A PHP Example

[article] [edit page] [discussion] [history]

From Humanitarian-FOSS Project Development Site

This page describes a simple PHP programming exercise.


Contents

Problem Statement

Write a stand-alone PHP progam that uses an associative array, a user-defined function, and a foreach loop to print a few Light Bulb Jokes. Your solution should generate a web page that looks something like this.

Tutorial (Optional)

Here's a simple exercise from the very nice PHP Tutorial from the PHP web site: Copy the following PHP-enabled web-page and save it in a file named hello.php in your helloworld eclipse workspace.(solutions provided)

<html>
 <head>
  <title>PHP Test</title>
 </head>
 <body>
 <?php echo '<p>Hello World</p>'; ?> 
 </body>
</html>

Open hello.php in your browser (URL = localhost/workspace/helloworld/hello.php) and view the HTML source.

An HTML Template

Click here for a HTML Template you can use.

Declaring an Associative Array

You can declare the associative array in the "<HEAD>" of the web page. The syntax for declaring and initializing a PHP associative array is as follows:

$array_name = array("key1"=>"value1", "key2"=>"value2",...,"keyN"=>"valueN");

In this case the array's keys will be the joke's target -- e.g., professors -- and the values would be the associated punch lines. For more on associate arrays see PHP Manual/Arrays.

Defining a PHP Function

The function can also be defined in the page's "<HEAD>". Here's an example PHP function definition:

<?php
function print_message($message)
{
    print("<b>Message:</b> $message <BR>");
}
?>

For more on PHP functions see PHP Tutorial/Functions.

The PHP foreach Loop

PHP's foreach loop is well suited for processing an associative array. For example, if the array is named $my_array, this loop will print its keys and values into the web page:

foreach ($my_array as $key=>$value)
{
  print("<b>Key:</b> $key <BR> <b>Value:</b> $value <BR>");
}

For more on PHP loops see PHP Tutorial/Control-Structures.

Solution

Click here for a complete solution.

Demo

1. Open a browser tab to Jokes Demo.

Personal tools