PHP Exercises: Group the elements of an array based on the given function
PHP: Exercise-83 with Solution
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'));
?>
Sample Output:
Array ( [3] => Array ( [0] => one [1] => two ) [5] => Array ( [0] => three ) [4] => Array ( [0] => four ) )
Flowchart:
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a PHP program to get the index of the last element for which the given function returns a truth value.
Next: Write a PHP program to check a flat list for duplicate values. Returns true if duplicate values exists and false if values are all unique.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/php-exercises/php-basic-exercise-83.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics