3v4l.org

run code in 300+ PHP versions simultaneously
<?php function insertNewNodeTest() { $array = array( 'a' => array( 'a_1' => 'a_1 text', ), ); $object = json_decode( json_encode( $array )); //** $object = new ArrayObject( $array, 0, "RecursiveArrayIterator" ); $iterator = new RecursiveIteratorIterator( new RecursiveArrayIterator( $object ), RecursiveIteratorIterator::CHILD_FIRST ); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// foreach( $iterator as $key => $current ) { // insert a new empty node if( $key == 'a_1' ) { $iterator->getInnerIterator()->offsetSet( 'a_2', new stdClass() ); } // add new leaf into the previously inserted node if( $key == 'a_2' ) { $current->ex_empty = 'not empty now'; } // add another leaf into the previously inserted node if( $key == 'a_2' ) { $current->second_leaf = 'leaf with property'; } // add third leaf WITH ITERATOR(!) instead of using the $current->third_leaf if( $key == 'a_2' && $iterator->getInnerIterator()->hasChildren() ) { $iterator->getInnerIterator()->getChildren()->offsetSet( 'third_leaf', 'leaf with iterator'); } } print_r($object); } insertNewNodeTest();
Output for 5.2.0 - 5.2.17, 5.3.0 - 5.3.29, 5.4.0 - 5.4.45, 5.5.0 - 5.5.38, 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 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.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
stdClass Object ( [a] => stdClass Object ( [a_1] => a_1 text [a_2] => stdClass Object ( [ex_empty] => not empty now [second_leaf] => leaf with property [third_leaf] => leaf with iterator ) ) )
Output for 5.0.0 - 5.0.5, 5.1.0 - 5.1.6
Fatal error: Call to undefined function json_decode() in /in/4D63R on line 13
Process exited with code 255.
Output for 4.4.2 - 4.4.9
Parse error: syntax error, unexpected ')', expecting '(' in /in/4D63R on line 15
Process exited with code 255.
Output for 4.3.0 - 4.3.1, 4.3.5 - 4.3.11, 4.4.0 - 4.4.1
Parse error: parse error, unexpected ')', expecting '(' in /in/4D63R on line 15
Process exited with code 255.
Output for 4.3.2 - 4.3.4
Parse error: parse error, expecting `'('' in /in/4D63R on line 15
Process exited with code 255.

preferences:
343.24 ms | 401 KiB | 460 Q