hnewbie
hnewbie

Reputation: 151

Shift an entire array to the by one position in php

For example: I have an array that looks like this: Array ( [0] => A [1] => B [2] => C [3] => D [4] => E [5] => F). and etc..

I want to push the entire array by 1 to the right, so it looks like this: ( [0] => 0 [1] => A [2] => B [3] => C [4] => D [5] => E [6] => F). and etc....

Edit: My bad. I didn't word my question properly. I'm hoping I don't confuse people trying to clarify. I'd like to continue to push the array until the end of the array length. For example $len is 7. I'd like to perform an action on the array before iterating to the next position. So it looks like this:

Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 0 [6] => A).

My first attempt at this problem was to create a for loop:

for ($i = 0; $i < $len; $i++) {
  echo $chars[$i + 1];
  array_unshift($chars, 0);
}

My loop gives me 7 B's, which isn't what I want.

Is what I'm describing possible?

Upvotes: 3

Views: 3125

Answers (2)

FirstOne
FirstOne

Reputation: 6217

You don't need a loop. To shift the array the same amount of times as the array size, you can use array_fill + array_merge:

$arr = array('A', 'B', 'C', 'D', 'E', 'F'); $len = count($arr);
$tmp = array_fill(0, $len, 0);
$arr = array_merge($tmp, $arr);

Output:

Array
(
    [0] => 0
    [1] => 0
    [2] => 0
    [3] => 0
    [4] => 0
    [5] => 0
    [6] => A
    [7] => B
    [8] => C
    [9] => D
    [10] => E
    [11] => F
)


If you just need to shift once, use it like so:

$arr = array('A', 'B', 'C', 'D', 'E', 'F');
array_unshift($arr, 0); // adds 0 to the first item
// array_pop($arr); // you can remove the last one, if needed

Output (removing the last item):

Array
(
    [0] => 0
    [1] => A
    [2] => B
    [3] => C
    [4] => D
    [5] => E
)

If you want to add more than one and they are different, you can also use array_merge:

$arr = array('A', 'B', 'C', 'D', 'E', 'F');
$arr = array_merge(array(0, 'foo', 'bar'), $arr);
// Output: Array ( [0] => 0 [1] => foo [2] => bar [3] => A [4] => B [5] => C [6] => D [7] => E [8] => F )

Upvotes: 3

u_mulder
u_mulder

Reputation: 54831

Line

array_unshift($chars, 0); 

is enough, without any loop:

$chars = ['a', 'b', 'c'];
array_unshift($chars, 0);
print_r($chars);  // [0, 'a', 'b', 'c']

Upvotes: 2

Related Questions