array_filter
array_filter(array $array, ?callable $callback = null, int $mode = 0): array
Filters array elements with a callback function.
C C23
C23
#include <stdio.h>
int main(void) {
int xs[] = {1, 2, 3, 4, 5, 6};
size_t n = sizeof xs / sizeof xs[0];
int evens[6];
size_t m = 0;
for (size_t i = 0; i < n; i++) { // hand-written filter: C has no filter-style higher-order function
if (xs[i] % 2 == 0) evens[m++] = xs[i];
}
printf("[");
for (size_t i = 0; i < m; i++) {
printf(i ? ", %d" : "%d", evens[i]);
}
printf("]\n");
return 0;
}
Output
[2, 4, 6]
C++ C++26
C++26
#include <iostream>
#include <vector>
int main() {
std::vector<int> xs = {1, 2, 3, 4, 5, 6};
std::vector<int> evens;
for (int x : xs) {
if (x % 2 == 0) evens.push_back(x);
}
std::cout << "[";
for (size_t i = 0; i < evens.size(); ++i) {
if (i) std::cout << ", ";
std::cout << evens[i];
}
std::cout << "]\n";
return 0;
}
Output
[2, 4, 6]
C# v11.0.100
v11.0.100
var xs = new List<int> { 1, 2, 3, 4, 5, 6 };
var evens = xs.Where(x => x % 2 == 0).ToList();
Console.WriteLine($"[{string.Join(", ", evens)}]");
Output
[2, 4, 6]
Go v1.27.4
v1.27.4
package main
import "fmt"
func main() {
a := []int{1, 2, 3, 4, 5, 6}
var b []int
for _, v := range a {
if v%2 == 0 {
b = append(b, v)
}
}
fmt.Println(b)
}
Output
[2 4 6]
Java v27.0.1
v27.0.1
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println(Arrays.toString(Arrays.stream(new int[]{1, 2, 3, 4, 5, 6}).filter(x -> x % 2 == 0).toArray()));
}
}
Output
[2, 4, 6]
JavaScript v26.13.1
v26.13.1
console.log([1, 2, 3, 4, 5, 6].filter(x => x % 2 === 0))
Output
[ 2, 4, 6 ]
PHP v8.6.0
v8.6.0
echo json_encode(array_values(array_filter([1, 2, 3, 4, 5, 6], fn($x) => $x % 2 === 0)));
Output
[2,4,6]
Python v3.15.2
v3.15.2
print(list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5, 6])))
Output
[2, 4, 6]
Rust v1.99.1
v1.99.1
fn main() {
let v: Vec<i32> = (1..=6).filter(|x| x % 2 == 0).collect();
println!("{:?}", v);
}
Output
[2, 4, 6]
TypeScript v26.13.1
v26.13.1
const xs: number[] = [1, 2, 3, 4, 5, 6];
console.log(xs.filter((x) => x % 2 === 0));
Output
[ 2, 4, 6 ]
Language differences
C: has no built-in containers or higher-order functions; the example uses fixed arrays/buffers and hand-written loops.
C++: no built-in filter; filters with copy_if or a hand-written loop.
Go: no built-in, needs a loop.
Java: uses Stream.filter.
PHP: array_filter preserves the original keys, so it is often wrapped in array_values to reindex.
Python: filter returns an iterator.
Rust: filter is a lazy iterator adapter.