-1

I have an array like

Array ( [0] => xyz [1] => 93049 [2] => London [3] => Telephone: 45687654 [4] => Telefax: 54478453248 [5] => [6] => )

Now i want to add a blank value in key position [1] and shift rest of the array to right side like

Array ( [0] => xyz [1] => [2] => 93049 [3] => London [4] => Telephone: 45687654 [5] => Telefax: 54478453248 [6] => [7] => )

How can i do that in PHP. Please suggest.

Adas
  • 309
  • 1
  • 18

4 Answers4

1
$original = array( '0', '2', '3', '4', '5' );
$inserted = array( '1' ); 
array_splice( $original, 1, 0, $inserted );
loadjang
  • 327
  • 1
  • 3
1

array_splice() function will solve your purpose.

Try this:

$original = array(
    'xyz', 93049, 'London', 'Telephone: 45687654', 'Telefax: 54478453248', '', '' 
);
echo '<pre>';
print_r($original);

Original array:

   Array
(
[0] => xyz
[1] => 93049
[2] => London
[3] => Telephone: 45687654
[4] => Telefax: 54478453248
[5] => 
[6] => 
)

$pos = 1;       // Position where you want to insert
$string = '';   // The string you want to insert
array_splice($original, $pos, 0, '');

print_r($original);

Final output:

  Array
(
[0] => xyz
[1] => 
[2] => 93049
[3] => London
[4] => Telephone: 45687654
[5] => Telefax: 54478453248
[6] => 
[7] => 
)
Indrasis Datta
  • 8,692
  • 2
  • 14
  • 32
0

array_splice can do the job :

<?php
$arr = Array( "xyz","93049","London","Telephone: 45687654","Telefax: 54478453248","","" );
$new = Array( "" );
array_splice( $arr,1,0,$new ); // INSERT THE $NEW ARRAY IN POSITION 1.
var_dump( $arr );
?>

The result looks like :

array (size=8)
  0 => string 'xyz' (length=3)
  1 => string '' (length=0)
  2 => string '93049' (length=5)
  3 => string 'London' (length=6)
  4 => string 'Telephone: 45687654' (length=19)
  5 => string 'Telefax: 54478453248' (length=20)
  6 => string '' (length=0)
  7 => string '' (length=0)

Or :

Array ( [0] => xyz [1] => [2] => 93049 [3] => London [4] => Telephone: 45687654 [5] => Telefax: 54478453248 [6] => [7] => ) 
-1

You can put a value that you recognize as a black space, arbitrarily...

for example, I, arbitrarily are considering that when the word "BLANK" appears, its a blank space... so:

Array ( [0] => xyz [1] => BLANK [2] => 93049 [3] => London [4] => Telephone: 45687654 [5] => Telefax: 54478453248 [6] => [7] => .........

It's not a clear way to resolve it, but if you are not looking for the cleanest way, it resolves.