array_reverse
array_reverse(array $array, bool $preserve_keys = false): array
Returns a new array with the elements in reversed order.
C C23
#include <stdio.h>
int main(void) {
const char *src[] = {"a", "b", "c"};
const char *dst[3];
for (int i = 0; i < 3; i++) {
dst[i] = src[3 - 1 - i];
}
for (int i = 0; i < 3; i++) {
printf("%s\n", dst[i]);
}
return 0;
}
c b a
C++ C++26
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<std::string> xs{"a", "b", "c"};
std::reverse(xs.begin(), xs.end());
for (const auto &s : xs) std::cout << s << "\n";
return 0;
}
c b a
C# v11.0.100
var xs = new[] { "a", "b", "c" };
foreach (string s in xs.Reverse()) {
Console.WriteLine(s);
}
c b a
Go v1.27.4
package main
import "fmt"
func main() {
xs := []string{"a", "b", "c"}
for i, j := 0, len(xs)-1; i < j; i, j = i+1, j-1 {
xs[i], xs[j] = xs[j], xs[i]
}
fmt.Println(xs)
}
[c b a]
Java v27.0.1
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> xs = new ArrayList<>(List.of("a", "b", "c"));
Collections.reverse(xs);
System.out.println(xs);
}
}
[c, b, a]
JavaScript v26.13.1
const xs = ["a", "b", "c"];
const reversed = xs.toReversed();
console.log(reversed, xs);
[ 'c', 'b', 'a' ] [ 'a', 'b', 'c' ]
PHP v8.6.0
$xs = ["a", "b", "c"];
$reversed = array_reverse($xs);
echo json_encode($reversed), "\n", json_encode($xs);
["c","b","a"] ["a","b","c"]
Python v3.15.2
xs = ["a", "b", "c"]
print(list(reversed(xs)), xs[::-1])
['c', 'b', 'a'] ['c', 'b', 'a']
Rust v1.99.1
fn main() {
let mut xs = vec!["a", "b", "c"];
xs.reverse();
println!("{:?}", xs);
}
["c", "b", "a"]
TypeScript v26.13.1
const xs: string[] = ["a", "b", "c"];
const reversed: string[] = xs.toReversed();
console.log(reversed, xs);
[ 'c', 'b', 'a' ] [ 'a', 'b', 'c' ]
Language differences
C: uses a hand-written index map dst[i] = src[n-1-i].
C++: std::reverse works in place.
C#: the easiest trap — List<T>.Reverse() mutates in place and returns void, while LINQ's Reverse() lazily yields a new sequence; same name, different semantics.
Go: hand-written two-pointer swap (1.21+ has slices.Reverse).
Java: Collections.reverse works in place.
JavaScript: historically reversed in place with reverse(); ES2023's toReversed() is the returns-new-array form (demonstrated here).
PHP: the key split is in-place versus a new sequence — array_reverse returns a new array and leaves the original untouched (preserve_keys = true keeps numeric keys).
Python: reversed() returns a lazy iterator and the xs[::-1] slice builds a new list.
Rust: the mainstream implementations elsewhere all work in place — Vec::reverse mutates the Vec; clone first if you need a fresh sequence.
TypeScript: same as JavaScript — reverse() reverses in place, toReversed() returns a new array (demonstrated here).