Question

How can this PHP code be changed to use a parameter to the function that you...

How can this PHP code be changed to use a parameter to the function that you would then pass $students in? (instead of using a global).
Also, can you show how to use a loop to handle any length of array? (instead of an array that is 3 elements).

<?php

$students = array(

    array('FName'=>'Jane', 'LName'=>'Doe', 'ClassScore'=>90),

    array('FName'=>'Bob', 'LName'=>'Joe', 'ClassScore'=>50),

    array('FName'=>'John', 'LName'=>'Doe', 'ClassScore'=>20)

    );

    //1. CalculateSum() Function

    function CalculateSum()

    {

        // Use $students array throughout the function.

        global $students;

        // Add the $students array ClassScores together.

        $Sum = $students[0]['ClassScore'] + $students[1]['ClassScore'] + $students[2]['ClassScore'];

        return $Sum;

    }

    

    // Print out the results.

    echo "Sum of scores = " . CalculateSum()."<br>" ;

   

    //2. CalculateAverage() Function

    function CalculateAverage()

    {

        // Use $students array throughout the function.

        global $students;

        // Use the CalculateSum() Function to find the Average.

        $Sum = CalculateSum();

        // Get the average by dividing the class score sum by the # of students.

        $Avg = $Sum / 3;

        

        return $Avg;

    }

    

    // Print out the results.

    echo "Average of scores = " . CalculateAverage() . "<br>";

   

    //3. FindMin() Function

    $MinArray = FindMin();

    // Create the function.

    function FindMin()

    {

        // Use $students array throughout the function.

        global $students;

        // Define variable to return a class score.

        $score1 = $students[0]['ClassScore'];

        $score2 = $students[1]['ClassScore'];

        $score3 = $students[2]['ClassScore'];

        

        // If score1 is lower than 2 & 3.

        if ($score1 <= $score2 && $score1 <= $score3)

        {

        return $students[0];

        }

        // If score2 is lower than 1 & 3.

        elseif (($score2 <= $score1 && $score2 <= $score3))

        {

            return $students[1];

        }

            // If score3 is lower than 1 & 2.

            else

            {

                return $students[2];

            }

    } // end FindMin().

    // Print out the results.

    echo "Minimum class score: " . $MinArray['FName'] . " " . $MinArray['LName'] ." ". $MinArray['ClassScore'] . "<br>";

    //4. FindMax() Function

    $MaxArray = FindMax();

    // Create the function.

    function FindMax()

    {  

        // Use $students array throughout the function.

        global $students;

        // Define variable to return a class score.

        $score1 = $students[0]['ClassScore'];

        $score2 = $students[1]['ClassScore'];

        $score3 = $students[2]['ClassScore'];

        

        // If score1 is higher than 2 & 3.

        if ($score1 >= $score2 && $score1 >= $score3)

        {

        return $students[0];

        }

        // If score2 is higher than 1 & 3.

        elseif (($score2 >= $score1 && $score2 >= $score3))

        {

        return $students[1];

        }

            // If score3 is higher than 1 & 2.

            else

            {

            return $students[2];

            }

    } // end FindMax().

    

    echo "Maximum class score: " . $MaxArray['FName'] . " " . $MaxArray['LName'] ." ". $MaxArray['ClassScore'] . "<br>";

?>

Homework Answers

Answer #1

Here we have changed all function definitions to accept a parameter. And the parameter needed to be passed while calling the function.

For making code useful for any no of elements and not just 3 we have used for loop and it iterates count($students) no of times, i.e no of elements in the array. Propper comments have been included.

Code:

<?php

$students = array(
    array('FName'=>'Jane', 'LName'=>'Doe', 'ClassScore'=>90),
    array('FName'=>'Bob', 'LName'=>'Joe', 'ClassScore'=>50),
    array('FName'=>'John', 'LName'=>'Doe', 'ClassScore'=>20)
    );
    //1. CalculateSum() Function
    function CalculateSum($students)
    {
        // initial sum  is zero
        $sum = 0;
        // Use $students array throughout the function.
        // global $students;
        // Add the $students array ClassScores together.
        for($i=0 ; $i<count($students); $i++)
            $sum += $students[$i]['ClassScore'];
        return $sum;
    }

    // Print out the results.
    // Here we passed $students to function 
    echo "Sum of scores = " . CalculateSum($students)."<br>" ;

    //2. CalculateAverage() Function
    function CalculateAverage($students)

    {
        // Use the CalculateSum() Function to find the Average.
        // passed $students as parameter
        $Sum = CalculateSum($students);
        // Get the average by dividing the class score sum by the no of students.
        $Avg = $Sum / count($students);
        return $Avg;

    }

    

    // Print out the results.

    echo "Average of scores = " . CalculateAverage($students) . "<br>";

   

    //3. FindMin() Function

    $MinArray = FindMin($students);

    // Create the function.
    function FindMin($students)

    {
        // assuming 1st elemenet is minimum
        $minVal = $students[0]['ClassScore'];
        $min=0;
        // Use for loop to check all elements
        for($i=0; $i<count($students); $i++){
            // if new minimum is found, set it to minVal
            if($minVal < $students[$i]['ClassScore']){
                $minVal = $students[$i]['ClassScore'];
                $min = $i;
            }
            
        }
        // return element of array that had minimum classscore
        return $students[$min];
    } // end FindMin().

    // Print out the results.

    echo "Minimum class score: " . $MinArray['FName'] . " " . $MinArray['LName'] ." ". $MinArray['ClassScore'] . "<br>";

    //4. FindMax() Function

    $MaxArray = FindMax($students);

    // Create the function.

    function FindMax($students)
    {  
        // assuming 1st elemenet is maximum
        $maxVal = $students[0]['ClassScore'];
        $max=0;
        // Use for loop to check all elements
        for($i=0; $i<count($students); $i++){
            // if new minimum is found, set it to minVal
            if($maxVal > $students[$i]['ClassScore']){
                $maxVal = $students[$i]['ClassScore'];
                $max = $i;
            }
            
        }
        // return element of array that had minimum classscore
        return $students[$max];
    } // end FindMax().

    echo "Maximum class score: " . $MaxArray['FName'] . " " . $MaxArray['LName'] ." ". $MaxArray['ClassScore'] . "<br>";

?>

Output:

Sum of scores = 160<br>Average of scores = 53.333333333333<br>Minimum class score: Jane Doe 90<br>Maximum class score: John Doe 20<br>
Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Be sure to ONLY Program this problem in C You are going to use an array...
Be sure to ONLY Program this problem in C You are going to use an array and a function, and print the values of that array backwards. Here's some guidelines to follow to help you out: 1. Setup your array manually (whichever values you want are ok, with as many as you want, and whichever datatype you prefer. That's all fine). 2. Be sure to call your function by sending two parameters to such function: the array’s length and the...
USE PYTHON LANGUAGE PLEASE FOCUS YOU SHOULD ENTER AN ARRAY AND THEN THE PROGRAM GIVE OUTPUT(...
USE PYTHON LANGUAGE PLEASE FOCUS YOU SHOULD ENTER AN ARRAY AND THEN THE PROGRAM GIVE OUTPUT( TRUE/ FALSE) QUIZ 8 Array Challenge Have the function ArrayChallenge(arr) take the array of numbers stored in arr and return the string true if any two numbers can be multiplied so that the answer is greater than double the sum of all the elements in the array. If not, return the string false. For example: if arr is [2, 5, 6, -6, 16, 2,...
<?php    if(isset($_GET['submit'])){ //sanitize the input        /* Check the error from the input: if...
<?php    if(isset($_GET['submit'])){ //sanitize the input        /* Check the error from the input: if input from user is empty -> get an error string variable if input is not empty -> use preg_match() to match the pattern $pattern = "/^[1-9][0-9]{2}(\.|\-)[0-9]{3}(\.|\-)[0-9]{4}$/"; -> if it's a matched, get a success string variable */           } ?> <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link...
IN C++ AS SIMPLE AS POSSIBLE ______ Re-write the given function, printSeriesSquareFifth,  to use a while loop...
IN C++ AS SIMPLE AS POSSIBLE ______ Re-write the given function, printSeriesSquareFifth,  to use a while loop (instead of for). • The function takes a single integer n as a parameter • The function prints a series between 1 and that parameter, and also prints its result • The result is calculated by summing the numbers between 1 and n (inclusive). If a number is divisible by 5, its square gets added to the result instead. • The function does not...
please fix code to delete by studentname import java.util.Scanner; public class COurseCom666 {     private String...
please fix code to delete by studentname import java.util.Scanner; public class COurseCom666 {     private String courseName;     private String[] students = new String[1];     private int numberOfStudents;     public COurseCom666(String courseName) {         this.courseName = courseName;     }     public String[] getStudents() {         return students;     }     public int getNumberOfStudents() {         return numberOfStudents;     }     public void addStudent(String student) {         if (numberOfStudents == students.length) {             String[] a = new String[students.length + 1];            ...
Assignment #4 – Student Ranking : In this assignment you are going to write a program...
Assignment #4 – Student Ranking : In this assignment you are going to write a program that ask user number of students in a class and their names. Number of students are limited to 100 maximum. Then, it will ask for 3 test scores of each student. The program will calculate the average of test scores for each student and display with their names. Then, it will sort the averages in descending order and display the sorted list with students’...
In this example you are allowed to use from the C standard library only functions for...
In this example you are allowed to use from the C standard library only functions for input and output (e.g. printf(), scanf()) Complete the following functions using C programming language: A positive integer number is said to be a perfect number if its positive factors, including 1 (but not the number itself), sum to the number. For example, 6 is a perfect number because 6=1+2+3. Complete the int Q6(intQ6_input, int perfect[])function that determines all perfect numbers smaller than or equal...
Questions: 1. (5 marks) Create a VB.NET Console Application that defines a function Smallest and calls...
Questions: 1. Create a VB.NET Console Application that defines a function Smallest and calls this function from the main program. The function Smallest takes three parameters, all of the Integer data type, and returns the value of the smallest among the three parameters. The main program should (1) Prompt a message (using Console.WriteLine) to ask the user to input three integers. (2) Call the built-in function Console.ReadLine() three times to get the user’s input. (3) Convert the user’s input from...
1. In C++, programmers can use a class to create a large number of instance variables...
1. In C++, programmers can use a class to create a large number of instance variables of the class's type. Group of answer choices True False 2. When a C++ programmer declares a function, they are required to state all of the following except Group of answer choices {} The type of data, if any, returned by the function The function name The type of data, if any, sent to the function 3. When a C++ programmer calls a function,...
Code Example 8-1 1. int count = 1; 2. int item_total = 0; 3. int item...
Code Example 8-1 1. int count = 1; 2. int item_total = 0; 3. int item = 0; 4. while (count < 4) { 5.      cout << "Enter item cost: "; 6.      cin >> item; 7.      item_total += item; 8.      ++count; 9. } 10. int average_cost = round(item_total / count); 11. cout << "Total cost: " << item_total << "\nAverage cost: " << average_cost; (Refer to Code Example 8-1.) If the user enters 5, 10, and 15 at the prompts, the output is: Total...