2

I'd like to change the beginning of my array in PHP. Currently I've got:

Array
(
  [0] => Bla##
  [1] => Bla##
  [2] => Bla##
  [3] => Bla##
  [4] => Bla##
  [5] => Bla##

but I want

Array
(
  [6] => Bla##
  [7] => Bla##
  [8] => Bla##
  [9] => Bla##
  [10] => Bla##
  [11] => Bla##

I used array_splice($array, 14, 0, 'Bla##'); to insert a value at a specific index of my array, but if I use this my array starts from 0 and not from 6.

Thanks in advance!

6
  • 2
    Why do you want it to be starting at position 6 and not 0? Commented Apr 28, 2017 at 13:30
  • Do you mean you want to change the indexes and leave the values the same? Commented Apr 28, 2017 at 13:30
  • @RiggsFolly yes, the values have to stay the same. Commented Apr 28, 2017 at 13:31
  • 3
    I would love to know why you want to do this? Commented Apr 28, 2017 at 13:32
  • And it may help with providing a good answer Commented Apr 28, 2017 at 13:32

3 Answers 3

5
$shift = 6;
$array = array_combine(range($shift, count($array)+$shift-1), $array);
Sign up to request clarification or add additional context in comments.

Comments

2

Just shift all the array positions forward by 6 0->6, 1->7 etc

    $array = [Bla##,Bla##,Bla##,Bla##,Bla##,Bla##];
    $newarray = array();    // Shifted array
    for ($i=0; $i < count($array);$i++) {  
          $newarray[$i+6] = $array[$i];  
    } 

Comments

0

You can use array_walk():

$n = 6;
array_walk($arr, function($value) use (&$x, &$n) {$x[$n] = $value; $n++;});

PHP Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.