Home >Backend Development >PHP Tutorial >How to Insert Elements into PHP Arrays at Specific Positions?

How to Insert Elements into PHP Arrays at Specific Positions?

Susan Sarandon
Susan SarandonOriginal
2024-11-25 10:43:14862browse

How to Insert Elements into PHP Arrays at Specific Positions?

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:

  • array_slice($array, 0, 3, true) extracts the first three elements of $array. The true argument ensures that the keys are preserved.
  • ["sample_key" => "sample_value"] is the element we want to insert.
  • array_slice($array, 3, count($array) - 1, true) extracts the remaining elements of $array starting from the fourth element.

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!

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