Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append array element with increasing the array count with key in PHP? [duplicate]

Tags:

arrays

php

I've array $a

$a[1] = "A";
$a[2] = "B";
$a[3] = "C";
$a[4] = "D";

Let's say, "X" is new value that I want append middle position in array, I want to add it to 2nd array position that is $a[2] but I want to increase the count keys of array that will become like:

$a[1] = "A";
$a[2] = "X";
$a[3] = "B";
$a[4] = "C";
$a[5] = "D";

In this case, I want to implement this within a loop by checking some conditions with if, I tried with slice and splice both are not working


1 Answers

I think , you can try this

$a = array( 'a', 'b', 'c', 'd', 'e' );
$b = array( 'x' ); 

array_splice( $a, 3, 0, $b  ); // splice in at position 3
like image 197
vjy tiwari Avatar answered Jul 20 '26 04:07

vjy tiwari