Inserting Elements into Arrays at Specific Positions
Inserting elements into arrays at specific positions is a common task that can be accomplished through a combination of slicing and union operators.
Suppose we have two arrays:
$array_1 = [ '0' => 'zero', '1' => 'one', '2' => 'two', '3' => 'three', ]; $array_2 = [ 'zero' => '0', 'one' => '1', 'two' => '2', 'three' => '3', ];
Our goal is to insert the array ['sample_key' => 'sample_value'] after the third element of both arrays.
Solution:
The array_slice() function allows us to extract portions of an array. We can combine this with the union array operator ( ) to recombine the parts in the desired order. The following code achieves our goal:
$res = array_slice($array, 0, 3, true) + ["sample_key" => "sample_value"] + array_slice($array, 3, count($array) - 1, true);
In this example:
Upon combining these parts using the union operator, the resulting array has the desired order:
print_r($res);
Output:
Array ( [zero] => 0 [one] => 1 [two] => 2 [sample_key] => sample_value [three] => 3 )
The above is the detailed content of How to Insert Elements into PHP Arrays at Specific Positions?. For more information, please follow other related articles on the PHP Chinese website!