3v4l.org

run code in 300+ PHP versions simultaneously
<?php $data[] = new stdClass; $data[0]->product_name = '1'; $data[0]->random_value = 'first'; $data[1]->product_name = '2'; $data[1]->random_value = 'second'; $data[2]->product_name = '2'; $data[2]->random_value = 'third'; $data[3]->product_name = '1'; $data[3]->random_value = 'fourth'; $data[4]->product_name = '3'; $data[4]->random_value = 'fifth'; $products = array(); foreach ($data as $data_object) { $products[$data_object->product_name][] = $data_object; } // product names are keys of $products var_dump(array_keys($products)); // products for each key var_dump($products);
Output for 8.1.23 - 8.1.33, 8.2.10 - 8.2.29, 8.3.0 - 8.3.27, 8.4.1 - 8.4.14
Fatal error: Uncaught Error: Attempt to assign property "product_name" on null in /in/7ejmW:7 Stack trace: #0 {main} thrown in /in/7ejmW on line 7
Process exited with code 255.
Output for 7.4.30
Warning: Creating default object from empty value in /in/7ejmW on line 7 Warning: Creating default object from empty value in /in/7ejmW on line 10 Warning: Creating default object from empty value in /in/7ejmW on line 13 Warning: Creating default object from empty value in /in/7ejmW on line 16 array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } array(3) { [1]=> array(2) { [0]=> object(stdClass)#1 (2) { ["product_name"]=> string(1) "1" ["random_value"]=> string(5) "first" } [1]=> object(stdClass)#4 (2) { ["product_name"]=> string(1) "1" ["random_value"]=> string(6) "fourth" } } [2]=> array(2) { [0]=> object(stdClass)#2 (2) { ["product_name"]=> string(1) "2" ["random_value"]=> string(6) "second" } [1]=> object(stdClass)#3 (2) { ["product_name"]=> string(1) "2" ["random_value"]=> string(5) "third" } } [3]=> array(1) { [0]=> object(stdClass)#5 (2) { ["product_name"]=> string(1) "3" ["random_value"]=> string(5) "fifth" } } }

preferences:
85.64 ms | 410 KiB | 5 Q