-1

I have an array

array(1) {
 [0]=>
  array(4) {
   [0]=>
   string(1) "1"
   [1]=>
   string(2) "10"
   [2]=>
   string(3) "100"
   [3]=>
   string(3) "200"
   }
}

I want to insert two element into the array which must be the 3rd and last element.

Output:

array(6) {
 [0]=>
  array(6) {
   [0]=>
   string(1) "1"
   [1]=>
   string(2) "10"
   [2]=>
   string(1) ""
   [3]=>
   string(3) "100"
   [4]=>
   string(3) "200"
   [5]=>
   string(1) ""
   }
}

how can i do this?

What I have tried

array_splice($input,3 ,0,"");

Then result become like this, the array not added in the middle

 array(6) {
 [0]=>
  array(6) {
   [0]=>
   string(1) "1"
   [1]=>
   string(2) "10"
   [2]=>
   string(1) ""
   [3]=>
   string(3) "100"
   [4]=>
   string(3) "200"
   [5]=>
   string(1) ""
   }
 [1]=>
 array(1) {
   [0]=>
   string(1) ""
 }
}
0

2 Answers 2

2

To insert in the middle of array, you can use array_splice with a length of 0.

array_splice($input, 3, 0, "");

To add to the array, you can use either array_push or [] operator

Sign up to request clarification or add additional context in comments.

6 Comments

The [] operator is preferred to push because you have no function call.
On the other hand, array_push allows appending multiple elements with single call :)
Absolutely right, plus it returns the new size, so you don't have to call count() on it. Always depends on the use case. :)
But my output would be added as an array(1) instead of the middle of the array(0)
@user2210819 you have to operate on $input[0] in your case, as $input[0] contains the array you want to modify.
|
0

By using array_splice you can insert element inside the array

 $array = [0 => 'Data', 1 => 'data2', 2=> 'data3'];
 array_splice($array, 1, 0, 'data append');
 var_dump($array);

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.