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"); // We will overwrite $val later so we want a reference foreach($target as $x => &$val) { // Temporary array $between = []; // Flag for if/when we find the first person $foundStart = false; foreach($val 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 $val = $between; } // Clean up reference variable so surprises don't happen unset($val); echo json_encode($target);
Output for 7.4.0 - 7.4.33, 8.0.1 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.26, 8.4.1 - 8.4.13
{"array":[{"Name":"John Doe","mail":"john-doe@gmail.com"},{"Name":"Thomas Dover","mail":"thomas-dover@icloud.com"},{"Name":"Alex Smith","mail":"alex-smith@gmx.com"}]}

preferences:
82.28 ms | 407 KiB | 5 Q