A PHP Example

This page describes a simple PHP programming exercise.

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) PHP Test  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 "" 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 "". Here's an example PHP function definition: "); } ?> 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("Key: $key  Value: $value "); } 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.