3v4l.org

run code in 300+ PHP versions simultaneously
<?php $a = array( 0 => 2, 1 => 3, 2 => 10, 3 => 3, 4 => 4, 5 => 8, 6 => 5, 7 => 1, 8 => 1 ); $b = array( 0 => "Hello world poduct", 1 => "Test Product", 2 => "Hello world poduct", 3 => "Hello world poduct", 4 => "Test Product", 5 => "Test Product", 6 => "Test Product", 7 => "Test Product", 8 => "Test Product", ); #foreach usage $result = []; $numbers = $a; $names = $b; foreach ($names as $index => $name) { $result[$name] ??= 0; $result[$name] += $numbers[$index]; } var_export($result, false); #for usage $result = []; for($i=0;$i<count($a);$i++){ if(!isset($result[$b[$i]])){ $result[$b[$i]] = 0; } $result[$b[$i]] += $a[$i]; } echo PHP_EOL; var_export($result); #array_walk $result = []; array_walk($a,function($v,$i) use (&$result,$b) { if(!isset($result[$b[$i]])){ $result[$b[$i]] = 0; } $result[$b[$i]] += $v; }); echo PHP_EOL; var_export($result);
Output for 8.0.1 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.27, 8.4.1 - 8.4.14
array ( 'Hello world poduct' => 15, 'Test Product' => 22, ) array ( 'Hello world poduct' => 15, 'Test Product' => 22, ) array ( 'Hello world poduct' => 15, 'Test Product' => 22, )

preferences:
106.38 ms | 407 KiB | 5 Q