3v4l.org

run code in 300+ PHP versions simultaneously
<?php function array_group_by($arr, $key) { if (!is_array($arr)) { trigger_error('array_group_by(): The first argument should be an array', E_USER_ERROR); } if (!is_string($key) && !is_int($key) && !is_float($key)) { trigger_error('array_group_by(): The key should be a string or an integer', E_USER_ERROR); } // Load the new array, splitting by the target key $grouped = []; foreach ($arr as $value) { $grouped[$value[$key]][] = $value; } // Recursively build a nested grouping if more parameters are supplied // Each grouped array value is grouped according to the next sequential key if (func_num_args() > 2) { $args = func_get_args(); foreach ($grouped as $key => $value) { $parms = array_merge([$value], array_slice($args, 2, func_num_args())); $grouped[$key] = call_user_func_array('array_group_by', $parms); } } return $grouped; } $rows = [ [ 'name' => 'This is apple', 'category' => 'apple', 'first_category' => 'fruit' ], [ 'name' => 'This is orange', 'category' => 'orange', 'first_category' => 'fruit' ], [ 'name' => 'This is pear', 'category' => 'pear', 'first_category' => 'fruit' ], [ 'name' => 'This is carrot', 'category' => 'carrot', 'first_category' => 'vegetable' ], [ 'name' => 'This is tomatoe', 'category' => 'tomatoe', 'first_category' => 'vegetable' ] ]; $items = array_group_by($rows, 'first_category'); var_dump($items);
Output for git.master, git.master_jit, rfc.property-hooks
array(2) { ["fruit"]=> array(3) { [0]=> array(3) { ["name"]=> string(13) "This is apple" ["category"]=> string(5) "apple" ["first_category"]=> string(5) "fruit" } [1]=> array(3) { ["name"]=> string(14) "This is orange" ["category"]=> string(6) "orange" ["first_category"]=> string(5) "fruit" } [2]=> array(3) { ["name"]=> string(12) "This is pear" ["category"]=> string(4) "pear" ["first_category"]=> string(5) "fruit" } } ["vegetable"]=> array(2) { [0]=> array(3) { ["name"]=> string(14) "This is carrot" ["category"]=> string(6) "carrot" ["first_category"]=> string(9) "vegetable" } [1]=> array(3) { ["name"]=> string(15) "This is tomatoe" ["category"]=> string(7) "tomatoe" ["first_category"]=> string(9) "vegetable" } } }

This tab shows result from various feature-branches currently under review by the php developers. Contact me to have additional branches featured.

Active branches

Archived branches

Once feature-branches are merged or declined, they are no longer available. Their functionality (when merged) can be viewed from the main output page


preferences:
28.73 ms | 408 KiB | 5 Q