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 git.master, git.master_jit, rfc.property-hooks
array ( 120 => array ( 'user_id' => 120, 'username' => 'test1', 'count' => 5, ), 110 => array ( 'user_id' => 110, 'username' => 'test2', 'count' => 2, ), )

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:
51.55 ms | 874 KiB | 4 Q