3v4l.org

run code in 300+ PHP versions simultaneously
<?php function array_to_anon_object($arr): object { $obj = new class {}; foreach ( $arr as $key => $value ) { $obj->{$key} = $value; } return $obj; } class EmptyClass {} function array_to_normal_object($arr, $className): object { $obj = new class {}; foreach ( $arr as $key => $value ) { $obj->{$key} = $value; } return $obj; } var_dump( json_encode([1,2,3]) ); var_dump( json_encode((object)[1,2,3]) ); var_dump( json_encode(array_to_anon_object([1,2,3])) ); var_dump( json_encode(array_to_normal_object([1,2,3], EmptyClass::class)) ); var_dump( json_encode(array_to_normal_object([1,2,3], stdClass::class)) );
based on kbVnu
Output for 7.2.0 - 7.2.34, 7.3.0 - 7.3.23, 7.4.0 - 7.4.13, 8.0.0
string(7) "[1,2,3]" string(19) "{"0":1,"1":2,"2":3}" string(19) "{"0":1,"1":2,"2":3}" string(19) "{"0":1,"1":2,"2":3}" string(19) "{"0":1,"1":2,"2":3}"