How to add array element with increasing number of keyed arrays in PHP?

I have an array $a

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

      

Let's say "X"

is a new value that I want to add the middle position at array

, I want to add it to the second position array

, which $a[2]

, but I want to increment the counter keys

array

, which will become:

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

      

In this case I want to implement it in a loop, checking some conditions with if, I tried using slice and splice, both don't work

+3


source to share


3 answers


Do it as shown 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

0


source


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

      

+3


source


Use php funtion for 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);
    ?>

      

+2


source







All Articles