array_unique
array_unique(array $array, int $flags = SORT_STRING): array
Removes duplicate values from an array.
C C23
C23
#include <stdio.h>
int main(void) {
int xs[] = {1, 2, 2, 3, 1};
size_t n = sizeof xs / sizeof xs[0];
int out[5];
size_t m = 0;
for (size_t i = 0; i < n; i++) { // O(n^2) dedup: C has no built-in containers
int dup = 0;
for (size_t j = 0; j < m; j++) {
if (out[j] == xs[i]) { dup = 1; break; }
}
if (!dup) out[m++] = xs[i];
}
printf("[");
for (size_t i = 0; i < m; i++) {
printf(i ? ", %d" : "%d", out[i]);
}
printf("]\n");
return 0;
}
Output
[1, 2, 3]
C++ C++26
C++26
#include <iostream>
#include <set>
#include <vector>
int main() {
std::vector<int> xs = {1, 2, 2, 3, 1};
std::set<int> seen(xs.begin(), xs.end()); // set dedups and sorts automatically
std::vector<int> unique(seen.begin(), seen.end());
std::cout << "[";
for (size_t i = 0; i < unique.size(); ++i) {
if (i) std::cout << ", ";
std::cout << unique[i];
}
std::cout << "]\n";
return 0;
}
Output
[1, 2, 3]
C# v11.0.100
v11.0.100
var xs = new List<int> { 1, 2, 2, 3, 1 };
Console.WriteLine($"[{string.Join(", ", xs.Distinct())}]");
Output
[1, 2, 3]
Go v1.27.4
v1.27.4
package main
import "fmt"
func main() {
a := []int{1, 2, 2, 3, 1}
seen := map[int]bool{}
var b []int
for _, v := range a {
if !seen[v] {
seen[v] = true
b = append(b, v)
}
}
fmt.Println(b)
}
Output
[1 2 3]
Java v27.0.1
v27.0.1
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
public class Main {
public static void main(String[] args) {
System.out.println(new ArrayList<>(new LinkedHashSet<>(List.of(1, 2, 2, 3, 1))));
}
}
Output
[1, 2, 3]
JavaScript v26.13.1
v26.13.1
console.log([...new Set([1, 2, 2, 3, 1])])
Output
[ 1, 2, 3 ]
PHP v8.6.0
v8.6.0
echo json_encode(array_values(array_unique([1, 2, 2, 3, 1])));
Output
[1,2,3]
Python v3.15.2
v3.15.2
print(list(dict.fromkeys([1, 2, 2, 3, 1])))
Output
[1, 2, 3]
Rust v1.99.1
v1.99.1
fn main() {
let mut seen = std::collections::HashSet::new();
let v: Vec<i32> = vec![1, 2, 2, 3, 1].into_iter().filter(|x| seen.insert(*x)).collect();
println!("{:?}", v);
}
Output
[1, 2, 3]
TypeScript v26.13.1
v26.13.1
const xs: number[] = [1, 2, 2, 3, 1];
console.log([...new Set(xs)]);
Output
[ 1, 2, 3 ]
Language differences
C: has no built-in containers or higher-order functions; the example uses fixed arrays/buffers and hand-written loops.
C++: deduplicates via std::set (resulting order is sorted).
Java: LinkedHashSet deduplicates while preserving order.
JavaScript: Set deduplicates while preserving order.
PHP: array_unique preserves the original keys (the example reindexes with array_values).
Python: set loses order while dict.fromkeys preserves it.