Average Salary Challenge
In this challenge, I want you to create a function that will calculate the average salary of the salaries in the job listings.
In the sandbox file for this section, I added a spot to output the average salary. I also added a comment where you should add your function.
<div class="bg-green-100 rounded-lg shadow-md p-6 my-6">
<h2 class="text-2xl font-semibold mb-4">Average Salary: <?php echo 'replace with your function call ?></h2>
</div>
Here is the function signature:
function calculateAverageSalary($jobListings) {
// Your code here
}
It will take in the entire $jobListings array. You will need to loop through the array and add up all of the salaries. Then you will need to divide that total by the number of salaries. Finally, you will need to return the average salary.
Hints
- You can use the
countfunction to get the number of items in an array. - You can either use the
array_sumfunction in combination witharray_columnto add up the salaries or loop over the$jobListingsarray using aforeachloop and add up the salaries using the+=operator. - Use the
formatSalaryfunction that we created to format the average salary.
Click For Solution 1
function calculateAverageSalary($jobListings) {
$totalSalary = 0;
$count = count($jobListings);
// Calculate the total salary
foreach ($jobListings as $job) {
$totalSalary += $job['salary'];
}
// Calculate the average salary
$averageSalary = ($count > 0) ? $totalSalary / $count : 0;
return formatSalary($averageSalary);
}
Explanation
- We initialize a
$totalSalaryvariable to 0. - We get the number of items in the
$jobListingsarray using thecountfunction and store it in a$countvariable. - We loop over the
$jobListingsarray using aforeachloop. - We add the salary of each job to the
$totalSalaryvariable using the+=operator. - We calculate the average salary by dividing the
$totalSalaryby the$countvariable. - We return the average salary using the
formatSalaryfunction.
Click For Solution 2
function calculateAverageSalary($jobListings) {
$salaries = array_column($jobListings, 'salary');
$totalSalary = array_sum($salaries);
$count = count($jobListings);
// Calculate the average salary
$averageSalary = ($count > 0) ? $totalSalary / $count : 0;
return formatSalary($averageSalary);
}
Explanation
- We use the
array_columnfunction to get an array of all of the salaries. - We use the
array_sumfunction to add up all of the salaries. - We get the number of items in the
$jobListingsarray using thecountfunction and store it in a$countvariable. - We calculate the average salary by dividing the
$totalSalaryby the$countvariable. - We return the average salary using the
formatSalaryfunction.