Introduction
Array transformation means changing, combining, or restructuring array data, while aggregation means calculating a single result from multiple array elements. PHP provides useful functions such as array_map(), array_reduce(), array_merge(), array_combine(), array_unique(), and array_sum(). In this chapter, you will practise these functions using practical examples based on student marks, employee records, product lists, and sales data. Array Transformation and Aggregation in PHP Practice Questions with Solutions to help you to understand the concepts.
Question 1: Convert All Names to Uppercase Using array_map()
Problem Statement
Create an array of employee names and convert every name into uppercase using the array_map() function.
PHP Solution
<?php
$employees = ["rahul", "priya", "amit", "neha"];
$uppercaseNames = array_map("strtoupper", $employees);
print_r($uppercaseNames);
?>
Sample Output
Array
(
[0] => RAHUL
[1] => PRIYA
[2] => AMIT
[3] => NEHA
)
Explanation
The array_map() function applies a specified function to every element of an array. Here, strtoupper() converts each employee name into uppercase and returns a new array.
Concepts Covered
array_map()function- Array transformation
- Uppercase conversion
- Processing array elements
Question 2: Increase Every Product Price by 10%
Problem Statement
Create an array containing product prices. Increase every price by 10% using array_map().
PHP Solution
<?php
$prices = [500, 1000, 1500, 2000];
$newPrices = array_map(function ($price) {
return $price + ($price * 10 / 100);
}, $prices);
print_r($newPrices);
?>
Sample Output
Array
(
[0] => 550
[1] => 1100
[2] => 1650
[3] => 2200
)
Explanation
The callback function receives each product price and calculates its value after adding 10%. The array_map() function applies this calculation to every element and returns a new array.
Concepts Covered
array_map()function- Anonymous functions
- Percentage calculations
- Array transformation
Question 3: Calculate the Total Sales Using array_sum()
Problem Statement
Create an array containing five daily sales amounts. Calculate the total sales using the array_sum() function.
PHP Solution
<?php
$sales = [2500, 3000, 1800, 4200, 3500];
$totalSales = array_sum($sales);
echo "Total Sales: Rs. " . $totalSales;
?>
Sample Output
Total Sales: Rs. 15000
Explanation
The array_sum() function calculates the sum of all numeric values in an array. It returns a single total instead of another array.
Concepts Covered
array_sum()function- Array aggregation
- Addition of numeric values
- Sales calculation
Question 4: Calculate the Average Marks Using array_sum() and count()
Problem Statement
Create an array containing marks of five students. Calculate the average marks using array_sum() and count().
PHP Solution
<?php
$marks = [85, 90, 75, 80, 70];
$totalMarks = array_sum($marks);
$totalStudents = count($marks);
$average = $totalMarks / $totalStudents;
echo "Total Marks: " . $totalMarks . "\n";
echo "Average Marks: " . $average;
?>
Sample Output
Total Marks: 400
Average Marks: 80
Explanation
The array_sum() function calculates the total marks, while count() returns the number of students. Dividing the total marks by the number of students gives the average.
Concepts Covered
array_sum()functioncount()function- Average calculation
- Array aggregation
Question 5: Calculate the Total Using array_reduce()
Problem Statement
Create an array containing monthly sales amounts. Calculate the total sales using the array_reduce() function.
PHP Solution
<?php
$sales = [12000, 15000, 18000, 14000];
$totalSales = array_reduce($sales, function ($total, $amount) {
return $total + $amount;
}, 0);
echo "Total Monthly Sales: Rs. " . $totalSales;
?>
Sample Output
Total Monthly Sales: Rs. 59000
Explanation
The array_reduce() function processes array elements one by one and combines them into a single result. The $total variable stores the accumulated value, while $amount represents the current sales amount. The final 0 is the initial value.
Concepts Covered
array_reduce()function- Array aggregation
- Accumulator
- Anonymous functions
Question 6: Combine Two Arrays Using array_merge()
Problem Statement
Create two arrays containing employee names. Combine both arrays into a single array using array_merge().
PHP Solution
<?php
$employees1 = ["Rahul", "Priya", "Amit"];
$employees2 = ["Neha", "Karan", "Simran"];
$allEmployees = array_merge($employees1, $employees2);
print_r($allEmployees);
?>
Sample Output
Array
(
[0] => Rahul
[1] => Priya
[2] => Amit
[3] => Neha
[4] => Karan
[5] => Simran
)
Explanation
The array_merge() function combines two or more arrays into one array. For numeric keys, the resulting array receives new sequential indexes.
Concepts Covered
array_merge()function- Combining arrays
- Numeric array indexes
- Array transformation
Question 7: Remove Duplicate Values Using array_unique()
Problem Statement
Create an array containing repeated product categories. Remove duplicate values using the array_unique() function.
PHP Solution
<?php
$categories = [
"Electronics",
"Clothing",
"Electronics",
"Furniture",
"Clothing",
"Books"
];
$uniqueCategories = array_unique($categories);
print_r($uniqueCategories);
?>
Sample Output
Array
(
[0] => Electronics
[1] => Clothing
[3] => Furniture
[5] => Books
)
Explanation
The array_unique() function removes duplicate values and keeps the first occurrence of each value. It preserves the original keys, so some numeric indexes may be missing.
Concepts Covered
array_unique()function- Removing duplicate values
- Array transformation
- Preserving array keys
Question 8: Create an Associative Array Using array_combine()
Problem Statement
Create two arrays: one containing employee names and another containing their departments. Combine them into an associative array using array_combine().
PHP Solution
<?php
$names = ["Rahul", "Priya", "Amit"];
$departments = ["IT", "HR", "Sales"];
$employees = array_combine($names, $departments);
print_r($employees);
?>
Sample Output
Array
(
[Rahul] => IT
[Priya] => HR
[Amit] => Sales
)
Explanation
The array_combine() function creates an associative array using the first array as keys and the second array as values. Both arrays must contain the same number of elements.
Concepts Covered
array_combine()function- Associative arrays
- Creating key-value pairs
- Array transformation
Question 9: Find the Highest and Lowest Sales Values
Problem Statement
Create an array containing monthly sales amounts. Find the highest and lowest sales values using max() and min().
PHP Solution
<?php
$sales = [15000, 22000, 18000, 30000, 12000];
$highestSales = max($sales);
$lowestSales = min($sales);
echo "Highest Sales: Rs. " . $highestSales . "\n";
echo "Lowest Sales: Rs. " . $lowestSales;
?>
Sample Output
Highest Sales: Rs. 30000
Lowest Sales: Rs. 12000
Explanation
The max() function returns the highest value in an array, while min() returns the lowest value. Both functions produce a single result from multiple array elements.
Concepts Covered
max()functionmin()function- Finding maximum and minimum values
- Array aggregation
Question 10: Calculate Department-Wise Total Sales Using array_reduce()
Problem Statement
Create a multidimensional array containing department names and sales amounts. Use array_reduce() to calculate the combined sales of all departments.
PHP Solution
<?php
$departments = [
["name" => "IT", "sales" => 25000],
["name" => "HR", "sales" => 18000],
["name" => "Sales", "sales" => 42000],
["name" => "Finance", "sales" => 30000]
];
$totalSales = array_reduce($departments, function ($total, $department) {
return $total + $department["sales"];
}, 0);
echo "Total Department Sales: Rs. " . $totalSales;
?>
Sample Output
Total Department Sales: Rs. 115000
Explanation
The array_reduce() function processes each department record. The callback accesses the "sales" value and adds it to the running total. After processing all records, the function returns the combined sales amount.
Concepts Covered
- Multidimensional arrays
array_reduce()function- Array aggregation
- Callback functions
- Department-wise data processing
Key Takeaways
- Use
array_map()to transform every element of an array. - Use
array_sum()to calculate the total of numeric array values. - Use
array_reduce()to combine array elements into a single result. - Use
array_merge()to combine multiple arrays. - Use
array_unique()to remove duplicate values. - Use
array_combine()to create an associative array from two arrays. - Use
count()to find the number of array elements. - Use
max()andmin()to find the highest and lowest values. - Array transformation creates or returns modified array data without requiring you to write a loop for every operation.
- Array aggregation helps calculate totals, averages, and other summary results.
Frequently Asked Questions (FAQs)
1. What is array transformation in PHP?
Array transformation means changing or restructuring array elements using functions such as array_map(), array_merge(), and array_unique().
2. What is array aggregation in PHP?
Array aggregation means processing multiple array elements to produce a single result, such as a total, average, highest value, or lowest value.
3. What does array_map() do in PHP?
The array_map() function applies a specified function to every element of an array and returns a new array containing the transformed values.
4. What is the difference between array_map() and array_filter()?
array_map() transforms array elements, while array_filter() selects only elements that satisfy a given condition.
5. What does array_reduce() do?
The array_reduce() function processes array elements one by one and combines them into a single result using a callback function.
6. How do you calculate the total of an array in PHP?
Use the array_sum() function:
$numbers = [10, 20, 30];
echo array_sum($numbers);
Output: 60
7. How do you combine two arrays in PHP?
Use the array_merge() function to combine two or more arrays into one array.
8. How do you remove duplicate values from an array?
Use the array_unique() function to remove duplicate values while keeping the first occurrence of each value.
9. What is the purpose of array_combine()?
The array_combine() function creates an associative array by using one array for keys and another array for values. Both arrays must have the same number of elements.
10. Can array transformation and aggregation be used with multidimensional arrays?
Yes. Functions such as array_map() and array_reduce() can process multidimensional arrays when their callback functions are designed to access nested values.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
