3v4l.org

run code in 300+ PHP versions simultaneously
<?php $array=[ ['invoice_id'=>'WUI_588','email'=>'abc@hotmail.com'], ['invoice_id'=>'WUI_588','email'=>'def@hotmail.com'], ['invoice_id'=>'WUI_589','email'=>'ninja@hotmail.com'], ['invoice_id'=>'WUI_589','email'=>'ghi@hotmail.com'], ['invoice_id'=>'WUI_590','email'=>'123@hotmail.com'], ['invoice_id'=>'WUI_590','email'=>'123@hotmail.com'], ['invoice_id'=>'WUI_591','email'=>'456@hotmail.com'], ['invoice_id'=>'WUI_591','email'=>'456@hotmail.com'] ]; foreach($array as $row){ // iterate all rows if(!isset($result[$row['invoice_id']])){ // if first occurrence of invoice_id... $result[$row['invoice_id']]=$row; // save the full row with invoice_id as the temporary key }else{ // if not the first occurrence of invoice_id... $result[$row['invoice_id']]['email'].=", {$row['email']}"; // concatenate the email value } } var_export(array_values($result));
Output for 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.26, 8.4.1 - 8.4.13
array ( 0 => array ( 'invoice_id' => 'WUI_588', 'email' => 'abc@hotmail.com, def@hotmail.com', ), 1 => array ( 'invoice_id' => 'WUI_589', 'email' => 'ninja@hotmail.com, ghi@hotmail.com', ), 2 => array ( 'invoice_id' => 'WUI_590', 'email' => '123@hotmail.com, 123@hotmail.com', ), 3 => array ( 'invoice_id' => 'WUI_591', 'email' => '456@hotmail.com, 456@hotmail.com', ), )

preferences:
141.66 ms | 409 KiB | 5 Q