3

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
  • 2
    array_splice() does what you need but it reindexes the values starting from 0. Commented Jul 25, 2017 at 12:36

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

No he don't want this:- eval.in/837358 .compare your output with OP's desired output
@Alive to Die , i was just giving teh example for his problem
2

Use php funtion to do this array_splice

<?php 
    $a = array( 'A', 'B', 'C', 'D', 'E' );
    $b = array( 'X' ); //  array optional or 
    //$b= 'x';
    array_splice( $a, 1, 0, $b  ); // splice in at position 1
    print_r($a);
    ?>

1 Comment

OP don't want what you said. check this output of your code:-eval.in/837699 and compare it with the desired output of OP. Both are different
0

Do it like below:-

<?php

$a = array( 1=>'A', 2=>'B', 3=>'C', 4=>'D' );

$b = array( 'x' ); 

array_splice( $a, 1, 0, $b  );

$a = array_combine(range(1, count($a)), array_values($a));

print_r($a);

Output:-https://eval.in/837366

Comments