You don't need to use the foreach for the insertion:
<?php
$target = json_decode(
'{
"array": [
{
"Name": "John Doe",
"mail": "john-doe@gmail.com"
},
{
"Name": "Alex Smith",
"mail": "alex-smith@gmx.com"
}
]
}',
true
);
$insert = [
'Name' => 'Thomas Dover',
'mail' => 'thomas-dover@icloud.com'
];
array_splice(
$target['array'],
1,
0,
[$insert]
);
echo json_encode($target, JSON_PRETTY_PRINT);
Output:
{
"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"
}
]
}
Added
In case you want to insert that item after "John Doe", not assuming its position:
foreach ($target['array'] as $index => $item) {
if ($item['Name'] === 'John Doe') {
array_splice(
$target['array'],
$index + 1,
0,
[$insert]
);
break;
}
}
Or before "Alex Smith":
foreach ($target['array'] as $index => $item) {
if ($item['Name'] === 'Alex Smith') {
array_splice(
$target['array'],
$index,
0,
[$insert]
);
break;
}
}
Or between "John Doe" and "Alex Smith":
foreach ($target['array'] as $index => $item) {
if ($item['Name'] === 'John Doe') {
++$index;
break;
}
}
for (; isset($target['array'][$index]); ++$index) {
$item = $target['array'][$index];
if ($item['Name'] === 'Alex Smith') {
array_splice(
$target['array'],
$index,
0,
[$insert]
);
break;
}
}
Or if the three need to be consecutive:
foreach ($target['array'] as $index => $item) {
if ($item['Name'] === 'John Doe') {
if (
isset($target['array'][$index+1])
&& $target['array'][$index+1]['Name'] === 'Alex Smith'
) {
array_splice(
$target['array'],
$index+1,
0,
[$insert]
);
}
break;
}
}
If you don't like nested if:
$found = false;
foreach ($target['array'] as $index => $item) {
if ($item['Name'] === 'John Doe') {
$found = true;
break;
}
}
if (
$found
&& isset($target['array'][$index+1])
&& $target['array'][$index+1]['Name'] === 'Alex Smith'
) {
array_splice(
$target['array'],
$index+1,
0,
[$insert]
);
}