Skip to main content Link Menu Expand (external link) Document Search Copy Copied

Homework 4 - PHP Introduction

Due: Thursday, October 12, 2023 at 11:59pm

This assignment must be completed individually.


  • Gain experience writing in PHP
  • Get ready to work on Sprint 3


In this assignment, we will be exploring the PHP language through solving a variety of problems. You are strongly encouraged to review the PHP documentation and utilize the language features that PHP provides. For example, you may want to review:


To begin, you should create a new PHP file, entitled homework4.php. You should copy and paste the template below into the file, adding your functions as you solve each problem. You should not include any code in this file outside of your implemented functions. Each function must return its result; do not print out your results in the function.

     * Homework 4 - PHP Introduction
     * Computing ID:
     * Resources used: [list any resources used to complete this assignment]
    // Your functions here

    // No closing php tag needed since there is only PHP in this file

Submit your completed homework4.php file to Gradescope.


You should also create a separate PHP file to test your Homework 4 functions. Call your functions with various inputs, including edge cases, and ensure that they behave as expected.

A template file is provided below, where we have “included” the homework4.php file we are writing.

?><!DOCTYPE html>
  <meta charset="UTF-8">  
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="author" content="your name">
  <meta name="description" content="include some description about your page">  
  <title>Homework 4 Test File</title>
<h1>Homework 4 Test File</h1>

<h2>Problem 1</h2>
    echo "Write tests for Problem 1 here\n";
    $test1 = [ [ "score" => 55, "max_points" => 100 ], [ "score" => 55, "max_points" => 100 ] ];
    echo calculateAverage($test1, false); // should be 55


Problem 1: Compute the Grade

Write a PHP function, calculateGrade() that accepts an array of project scores and an option specifying whether the score with the lowest percentage points will be dropped. Each project score in the array is an associative array with keys “score” and “max_points”; for example:

[ "score" => 55, "max_points" => 100 ]

The drop option will be given as a boolean value where true means drop the lowest project score and false means do not drop any scores. The lowest score is determined based on percentage of points awarded (for example, a 55/100 is 55% while a 7/10 is 70%, so the 55/100 is dropped). If there are multiple lowest project scores (i.e., same percentages), you decide which one to drop. The function must return the overall average of the project scores (100 * total scored points / total available points) rounded to three decimal places.

function calculateGrade($scores, $drop) { /*...*/ }

Problem 2: Gridding

Write a PHP function which takes in the width and height of a grid (in number of tiles):

function gridCorners($width, $height) { /*...*/ }

Each tile in the grid is numbered, starting at the bottom-left and going bottom-to-top, left to right. For example, if the user calls our function with width = 3 and height = 4, the grid would be:

 4  8  12
 3  7  11
 2  6  10
 1  5   9

The function gridCorners should return a comma-separated string that represents all unique tiles that are in the corner “brackets”, in numerical order. A “bracket” is defined as the corner tile and its adjacent neighbors. For example, the top-left bracket of the example above is:

 4  8

In this case, our function should return:

1, 2, 3, 4, 5, 8, 9, 10, 11, 12

Since the values should be unique, 5 and 8 are not repeated in the output. That is, the brackets overlap in this example.

If the grid doesn’t have a width or height of at least two, the function should return the ordered tiles of all the edges. If there are no tiles to be printed, return an empty string.

Note: The grids may get large! Too large for us to create a 2-dimensional array! So, you should avoid creating an array to store the grid; however, you may want to store the tiles you plan to return in your output in an array, using a PHP method to sort, uniquify, and combine the array into the appropriate return string. (Remember, the output string will have at most 12 tiles.)

Problem 3: Ready to go Shopping

Write a PHP function that accepts one or more associative arrays containing shopping lists and returns a merged items list in alphabetical order. There should not be duplicate entries in the merged list.

A shopping list is an associative array of the form:

    "user" => "Full Name",
    "list" => [ "item", ... , "item" ]

For example, if the incoming lists are:

$list1 = [ "user" => "Fred", 
           "list" => ["frozen pizza", "bread", "apples", "oranges"]

$list2 = [ "user" => "Wilma",
           "list" => ["bread", "apples", "coffee"]

Calling the function on these shopping lists:

combineShoppingLists($list1, $list2);

will return a merged items list of items to buy and which user wanted them.

    "apples" => [ "Fred", "Wilma" ],
    "bread" => [ "Fred", "Wilma" ],
    "coffee" => [ "Wilma" ],
    "frozen pizza" => [ "Fred" ],
    "oranges" => [ "Fred" ]

Problem 4: Validate Email

Write a PHP function that validates an email address based on the criteria below. If the email is valid, return true; if not, return false. You may want to consider writing a regular expression to verify the email address. Wikipedia has a well-documented discussion of regular expressions.

function validateEmail($email) { /*...*/ }

We will consider an email to be valid if:

  1. It contains an @ symbol followed by at least one period-separated domain name (i.e., or
  2. The characters following the @ symbol may only be alpha-numeric (a to z, A to Z, and 0 to 9) along with periods (.) and hyphens (-).
  3. the characters before the @ symbol may contain:
    • uppercase and lowercase letters A to Z and a to z
    • digits 0 to 9
    • certain printable special characters -_+
    • a dot (.), which may not be the first or last character

For example, consider the following calls:

validateEmail(""); // returns true
validateEmail(""); // returns true
validateEmail(""); // returns true
validateEmail(""); // returns false

Additionally, the function may be supplied with an optional parameter $regex, which also checks that the email address matches a more constrained format defined by the regular expression provided. For example, calling the function with the regular expression /^[a-z][a-z][a-z]?[0-9][a-z][a-z]?[a-z]?$/ will validate UVA email addresses:

validateEmail("", "/^[a-z][a-z][a-z]?[0-9][a-z][a-z]?[a-z]?$/"); // returns true
validateEmail("", "/^[a-z][a-z][a-z]?[0-9][a-z][a-z]?[a-z]?$/"); // returns false

Along with performing this additional validation step, the earlier validation functionality must also still be used. For example, we may constrain our verification to only alphabetical emails:

validateEmail("", "/^[a-z\.@]+$/"); // returns true
validateEmail("", "/^[a-z\.@]+$/"); // returns false (but matches this regex)
validateEmail("", "/^[a-z\.@]+$/"); // returns false


Submit your homework4.php PHP file to Gradescope in the “Homework 4” submission. Remember that this is an individual assignment.

Note: You will be allowed to submit a maximum of 15 times to Gradescope. Please utilize your local development environment or the cs4640 server to test your PHP code and verify that the output matches what is expected.

Grading Rubric

This homework is worth 50 points, and will be autograded by Gradescope using the following rubric:

  • 10 points - Problem 1
  • 15 points - Problem 2
  • 15 points - Problem 3
  • 10 points - Problem 4

Academic Integrity

For this assignment, you may not share your solutions publicly.

Use of Generative AI

For Homework 4, you are not allowed to use generative AI tools to help you solve this problem.