Home >Backend Development >PHP Tutorial >How Can I Insert Elements into PHP Arrays at Specific Indices Using `array_slice()` and the Union Operator?

How Can I Insert Elements into PHP Arrays at Specific Indices Using `array_slice()` and the Union Operator?

DDD
DDDOriginal
2024-11-28 11:05:12580browse

How Can I Insert Elements into PHP Arrays at Specific Indices Using `array_slice()` and the Union Operator?

Inserting Elements into Arrays at Specific Positions

Consider two arrays:

$array_1 = array(
  '0' => 'zero',
  '1' => 'one',
  '2' => 'two',
  '3' => 'three',
);

$array_2 = array(
  'zero'  => '0',
  'one'   => '1',
  'two'   => '2',
  'three' => '3',
);

To insert array('sample_key' => 'sample_value') after the third element of each array:

Use array_slice() and Array Union Operator

The array_slice() function extracts parts of an array, while the union array operator ( ) recombines those parts.

$res = array_slice($array, 0, 3, true) +
    array("my_key" => "my_value") +
    array_slice($array, 3, count($array)-3, true);

Example

$array = array(
  'zero'  => '0',
  'one'   => '1',
  'two'   => '2',
  'three' => '3',
);
$res = array_slice($array, 0, 3, true) +
    array("my_key" => "my_value") +
    array_slice($array, 3, count($array) - 1, true) ;
print_r($res);

Output:

Array
(
    [zero] => 0
    [one] => 1
    [two] => 2
    [my_key] => my_value
    [three] => 3
)

The above is the detailed content of How Can I Insert Elements into PHP Arrays at Specific Indices Using `array_slice()` and the Union Operator?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn