3v4l.org

run code in 500+ PHP versions simultaneously
<?php $arr = [ [ 'user_id' => 120, 'username' => 'test1', 'count' => 2 ], [ 'user_id' => 120, 'username' => 'test1', 'count' => 3 ], [ 'user_id' => 110, 'username' => 'test2', 'count' => 2 ] ]; /** loop through "$arr" and sum the "count" values based on the "user_id" */ $result = array_reduce($arr, function ($a, $c) { /** index the resulting array by the "user_id" value which allows for instant lookup in case of duplicate "user_id" value */ $a[$c['user_id']] = [ 'user_id' => $c['user_id'], 'username' => $c['username'], /** sum the "count" values * the first iteration will have an empty array * so we should check for existance before getting the value in order to prevent bugs */ 'count' => ($a[$c['user_id']]['count'] ?? 0) + $c['count'] ]; return $a; }, []); var_export($result);
Output for 7.4.30, 8.1.23 - 8.1.34, 8.2.10 - 8.2.30, 8.3.0 - 8.3.30, 8.4.1 - 8.4.21, 8.5.0 - 8.5.6
array ( 120 => array ( 'user_id' => 120, 'username' => 'test1', 'count' => 5, ), 110 => array ( 'user_id' => 110, 'username' => 'test2', 'count' => 2, ), )

preferences:
78.91 ms | 875 KiB | 4 Q