PHP Exercises: Group the elements of an array based on the given function
83. Group Array Elements by Callback Result
Write a PHP program to group the elements of an array based on the given function.
Sample Solution:
PHP Code:
<?php
// License: https://bit.ly/2CFA5XY
// Function definition for 'groupBy' that takes an array of items and a grouping function as parameters
function groupBy($items, $func)
{
// Initialize an empty associative array to store the grouped items
$group = [];
// Iterate through each item in the array
foreach ($items as $item) {
// Check if the grouping function is a callable function or a valid function name
if ((!is_string($func) && is_callable($func)) || function_exists($func)) {
// If callable, use 'call_user_func' to get the key and group the item
$key = call_user_func($func, $item);
$group[$key][] = $item;
}
// Check if the item is an object
elseif (is_object($item)) {
// If an object, use the property specified by the grouping function as the key and group the item
$group[$item->{$func}][] = $item;
}
// Check if the item has a key specified by the grouping function
elseif (isset($item[$func])) {
// If set, use the specified key as the grouping key and group the item
$group[$item[$func]][] = $item;
}
}
// Return the associative array containing the grouped items
return $group;
}
// Call 'groupBy' with an array of strings and a grouping function based on string length, then display the result using 'print_r'
print_r(groupBy(['one', 'two', 'three', 'four'], 'strlen'));
?>
Explanation:
- Define groupBy Function:
- The groupBy function takes two parameters:
- $items: an array of items to group.
- $func: a function or property name used to determine the grouping criteria.
- Initialize Grouping Structure:
- An empty associative array $group is created to store the grouped items.
- Iterate Through Items:
- A foreach loop iterates over each item in the $items array.
- Check Grouping Function:
- Callable Function:
- If $func is a callable function, call_user_func($func, $item) is used to invoke it and get the key for grouping.
- The item is added to $group under that key.
- Object Property:
- If the item is an object, it checks if $func corresponds to a property of the object and groups the item by that property.
- Array Key:
- If the item is an associative array and the key specified by $func exists, it uses that key to group the item.
- Return Grouped Items:
- After processing all items, the function returns the $group associative array containing the grouped results.
- Example Usage:
- The function is called with an array of strings and the strlen function to group the strings by their length.
- The result is displayed using print_r, showing how the strings are grouped based on their lengths (e.g., all strings with length 3 will be in one group).
- Purpose:
- The groupBy function provides a flexible way to organize and categorize items in an array based on custom criteria, whether through a function, object property, or array key.
Output:
Array ( [3] => Array ( [0] => one [1] => two ) [5] => Array ( [0] => three ) [4] => Array ( [0] => four ) )
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP script to group elements of an array into sub-arrays based on the result of a provided function.
- Write a PHP script to classify elements into groups using a callback and return an associative array of these groups.
- Write a PHP function to aggregate array values by computed key and output grouped results.
- Write a PHP script to partition an array into groups where each group shares the same value as returned by a custom function.
Go to:
PREV : Index of Last Element Matching a Condition.
NEXT : Duplicate Value Checker in a Flat List.
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.