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
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,...
Code in Java SAMPLE PROGRAM OUTPUT Because there are several different things your program might do...
Code in Java SAMPLE PROGRAM OUTPUT Because there are several different things your program might do depending upon what the user enters, please refer to the examples below to use to test your program. Run your final program one time for each scenario to make sure that you get the expected output. Be sure to format the output of your program so that it follows what is included in the examples. Remember, in all examples bold items are entered by...
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...
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’...
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...
0. Introduction. In this laboratory assignment, you will write a Python class called Zillion. The class...
0. Introduction. In this laboratory assignment, you will write a Python class called Zillion. The class Zillion implements a decimal counter that allows numbers with an effectively infinite number of digits. Of course the number of digits isn’t really infinite, since it is bounded by the amount of memory in your computer, but it can be very large. 1. Examples. Here are some examples of how your class Zillion must work. I’ll first create an instance of Zillion. The string...
Leave comments on code describing what does what Objectives: 1. To introduce pointer variables and their...
Leave comments on code describing what does what Objectives: 1. To introduce pointer variables and their relationship with arrays 2. To introduce the dereferencing operator 3. To introduce the concept of dynamic memory allocation A distinction must always be made between a memory location’s address and the data stored at that location. In this lab, we will look at addresses of variables and at special variables, called pointers, which hold these addresses. The address of a variable is given by...
**please write code with function definition taking in input and use given variable names** for e.g....
**please write code with function definition taking in input and use given variable names** for e.g. List matchNames(List inputNames, List secRecords) Java or Python Please Note:    * The function is expected to return a STRING_ARRAY.      * The function accepts following parameters:      *  1. STRING_ARRAY inputNames      *  2. STRING_ARRAY secRecords      */ Problem Statement Introduction Imagine you are helping the Security Exchange Commission (SEC) respond to anonymous tips. One of the biggest problems the team faces is handling the transcription of the companies reported...
STRICT DOWNVOTE IF NOT DONE FULLY, WILL REPORT ALSO IF COPY PASTED OR MODIFIED ANSWER Develop...
STRICT DOWNVOTE IF NOT DONE FULLY, WILL REPORT ALSO IF COPY PASTED OR MODIFIED ANSWER Develop a class, using templates, to provide functionality for a set of recursive functions. The functions specified as recursive must be written recursively (not iterativly). The UML class specifications are provided below. A main will be provided. Additionally, a make file will need to be developed and submitted. ● Recursion Set Class The recursion set template class will implement the template functions. recursionSet -length: int...
STRICT DOWNVOTE IF NOT DONE FULLY, WILL REPORT ALSO IF COPY PASTED OR MODIFIED ANSWER Develop...
STRICT DOWNVOTE IF NOT DONE FULLY, WILL REPORT ALSO IF COPY PASTED OR MODIFIED ANSWER Develop a class, using templates, to provide functionality for a set of recursive functions. The functions specified as recursive must be written recursively (not iterativly). The UML class specifications are provided below. A main will be provided. Additionally, a make file will need to be developed and submitted. ● Recursion Set Class The recursion set template class will implement the template functions. recursionSet -length: int...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT