-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) ""
 }
}
user2210819
  • 147
  • 2
  • 14

2 Answers2

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

Maxim Krizhanovsky
  • 24,757
  • 5
  • 49
  • 85
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);
Shushant
  • 1,577
  • 1
  • 12
  • 23