0

Initially i have an array list like this:

[
  [
    "hi",
    "hi",
    "hi",
    "",
    "hi",
    "2021-11-29 00:00:00",
    "4"
  ],
  [
    "custom title",
    "new custom",
    "customurl.com",
    "https://wpsn.test/wp-content/uploads/2021/09/vnech-tee-blue-1.jpg",
    "Custom Description",
    "2022-01-12 00:00:00",
    "4"
  ],
  [
    "new title",
    "suvro",
    "www.suvro.com",
    "",
    "new description",
    "2022-01-26 00:00:00",
    "4"
  ]
]

I want to add 'custom' at position 1 in each array - something like this:

[
  [
    "hi",
    "custom",
    "hi",
    "hi",
    "",
    "hi",
    "2021-11-29 00:00:00",
    "4"
  ],
  [
    "custom title",
    "custom",
    "new custom",
    "customurl.com",
    "https://wpsn.test/wp-content/uploads/2021/09/vnech-tee-blue-1.jpg",
    "Custom Description",
    "2022-01-12 00:00:00",
    "4"
  ],
  [
    "new title",
    "custom",
    "suvro",
    "www.suvro.com",
    "",
    "new description",
    "2022-01-26 00:00:00",
    "4"
  ]
]

What is the appropriate way to push this 'custom' in php, without iterating over the arrays?

4
  • Does this answer your question? Insert new item in array on any position in PHP Commented Apr 28, 2022 at 13:21
  • @DefinitelynotRafal no, this was for only one array, but i have multiple array items to insert 'custom' at position 1. Commented Apr 28, 2022 at 13:29
  • ...then call it in a loop. Commented May 27, 2022 at 5:51
  • Also viable for your scenario: 3v4l.org/1mle5 Commented May 27, 2022 at 6:05

2 Answers 2

0

You can do like this :

foreach ($data as $key => $value) {
    array_splice($data[$key], 1, 0, "custom");
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the array_map function for that:

$newArray = array_map(function($el) {
    array_splice($el, 1, 0, "custom"); // Insert "custom" at position 1
    return $el;
}, $array); // $array is the array you want to modify

Or just a simple foreach:

foreach($array as $index => $el) {
    array_splice($array[$index], 1, 0, "custom");
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.