3v4l.org

run code in 150+ php & hhvm versions
Bugs & Features
<?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.6.23, 7.0.0 - 7.1.0
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 hhvm-3.10.0 - 3.12.0
stdClass Object ( [a] => stdClass Object ( [a_1] => a_1 text ) )
Output for 5.0.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.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.