$result = array_splice( $yourArray, 0, 1 );
... should do the trick. See array_splice.
Answer from Decent Dabbler on Stack OverflowVideos
How does array_shift work with associative arrays?
$user = ['name' => 'John', 'age' => 25];
$first = array_shift($user);
print_r($user); // ['age' => 25]
echo $first; // John
It removes the first key-value pair based on internal order.What is the difference between array_shift and array_pop?
$arr = [1, 2, 3];
array_shift($arr); // removes 1 from start
array_pop($arr); // removes last element
array_shift removes from the beginning, array_pop removes from the end.$result = array_splice( $yourArray, 0, 1 );
... should do the trick. See array_splice.
You could use each like:
$b = array(1=>2, 3=>4, 7=>3);
while(1) {
list(
value) = each($b);
if (empty($key))
break;
echo "
val\n";
}
Iterating the array with each will keep its last position.
This is what array_splice does for you. It even lets you insert new entries there if you so choose.
For this specific case you use:
array_splice($array, 3, 1);
$array = array("banana", "apple", "raspberry", "kiwi", "cherry", "nuts");
$key = array_search('kiwi', $array);
unset($array[$key]);
$array = array_values($array);
print_r($array);
Output:
Array ( [0] => banana [1] => apple [2] => raspberry [3] => cherry [4] => nuts )
Try this :
$array = array_slice($array, 10);
for more information, look here.
I think you might be looking for array_splice, which directly modifies the array (same as array_shift), instead of returning a new array.
$n = 2; // number of elements to shift
array_splice($array, 0, $n);
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 )
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']