array_unshift
array_unshift(array &$array, mixed ...$values): int
Prepends one or more elements to the beginning of the array and returns the new element count.
C C23
#include <stdio.h>
#include <string.h>
int main(void) {
const char *queue[8] = {"b", "c"};
int size = 2;
memmove(queue + 1, queue, size * sizeof(char *));
queue[0] = "a";
size++;
for (int i = 0; i < size; i++) {
printf("%s\n", queue[i]);
}
printf("size=%d\n", size);
return 0;
}
a b c size=3
C++ C++26
#include <iostream>
#include <vector>
int main() {
std::vector<std::string> queue{"b", "c"};
queue.insert(queue.begin(), "a");
for (const auto &s : queue) std::cout << s << "\n";
std::cout << "size=" << queue.size() << "\n";
return 0;
}
a b c size=3
C# v11.0.100
var queue = new List<string> { "b", "c" };
queue.Insert(0, "a");
Console.WriteLine(string.Join("\n", queue));
Console.WriteLine($"count={queue.Count}");
a b c count=3
Go v1.27.4
package main
import "fmt"
func main() {
queue := []string{"b", "c"}
queue = append([]string{"a"}, queue...)
for _, s := range queue {
fmt.Println(s)
}
fmt.Printf("len=%d\n", len(queue))
}
a b c len=3
Java v27.0.1
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> queue = new ArrayList<>(List.of("b", "c"));
queue.add(0, "a");
queue.forEach(System.out::println);
System.out.println("size=" + queue.size());
}
}
a b c size=3
JavaScript v26.13.1
const queue = ["b", "c"];
const n = queue.unshift("a");
console.log(queue, n);
[ 'a', 'b', 'c' ] 3
PHP v8.6.0
$queue = ["b", "c"];
$n = array_unshift($queue, "a");
echo json_encode($queue), "\n", $n;
["a","b","c"] 3
Python v3.15.2
queue = ["b", "c"]
queue.insert(0, "a")
print(queue, len(queue))
['a', 'b', 'c'] 3
Rust v1.99.1
fn main() {
let mut queue = vec!["b", "c"];
queue.insert(0, "a");
println!("{:?} {}", queue, queue.len());
}
["a", "b", "c"] 3
TypeScript v26.13.1
const queue: string[] = ["b", "c"];
const n = queue.unshift("a");
console.log(queue, n);
[ 'a', 'b', 'c' ] 3
Language differences
C: idiomatically uses memmove to shift existing elements back one slot to free the head.
C++: insert(begin(), x).
C#: Insert(0, x).
Go: no built-in prepend; the idiom is append([]T{x}, s...) building a new slice (Go 1.21+ also offers slices.Insert(s, 0, x)).
Java: add(0, x).
JavaScript: unshift behaves the same (as in PHP, still O(n)).
PHP: head insertion, the counterpart of shift, is likewise O(n) — array_unshift prepends multiple values in one call and returns the new count (keeping the given order); other languages have no dedicated name and use the generic insert-at-index form.
Python: insert(0, x) (the generic insert-at-index form); queue code idiomatically uses deque.appendleft.
Rust: Vec::insert(0, x) (the generic form).
TypeScript: same as JavaScript.