3v4l.org

run code in 300+ PHP versions simultaneously
<?php $json = '{"array":[{"Name": "John Doe", "mail": "john-doe@gmail.com"}, {"Name": "Alex Smith", "mail": "alex-smith@gmx.com"}]}'; $target = json_decode($json, true); $insert = array("Name"=>"Thomas Dover", "mail"=>"thomas-dover@icloud.com"); // Temporary array $between = []; // Flag for if/when we find the first person $foundStart = false; foreach($target['array'] as $key => $v) { // If we found the first person previously, and this is our second person if($foundStart && 'Alex Smith' === $v['Name']) { // Insert $between[] = $insert; // Reset the flag just in case the second person is found again $foundStart = false; }elseif('John Doe' === $v['Name']){ // Flag that we found the first person $foundStart = true; } // No matter what, append our current item to the temp array $between[] = $v; } // Overwrite our original loop's variable with our temporary $target['array'] = $between; echo json_encode($target);

preferences:
24.6 ms | 405 KiB | 5 Q