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
Release: 2024-11-28 11:05:12
Original
497 people have browsed it

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',
);
Copy after login

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);
Copy after login

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);
Copy after login

Output:

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

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template