Array Functions

High-value array helpers: map/filter/reduce-like workflows in PHP.

On this page

Why Array Helpers Matter

PHP has powerful array helpers that can replace manual loops. They often make code shorter and clearer when used correctly.

array_map (Transform)

array_map transforms each element and returns a new array.

<?php
$numbers = [1, 2, 3];

$squared = array_map(function ($n) {
  return $n * $n;
}, $numbers);

print_r($squared); // [1, 4, 9]

array_filter (Filter)

array_filter keeps elements that pass a condition.

<?php
$items = ['php', '', 'mysql', '   '];

$clean = array_filter($items, function ($v) {
  return trim($v) !== '';
});

print_r(array_values($clean));

array_reduce (Aggregate)

array_reduce reduces an array into a single value (sum, hash, grouping, etc.).

<?php
$prices = [100, 250, 80];

$total = array_reduce($prices, function ($acc, $p) {
  return $acc + $p;
}, 0);

echo $total; // 430

array_column (Pick a Column)

When you have a list of associative arrays (records), array_column can extract a single field efficiently.

<?php
$users = [
  ['id' => 1, 'name' => 'Ozan'],
  ['id' => 2, 'name' => 'Ayse'],
];

$names = array_column($users, 'name');
print_r($names);

Production Tip

Array helpers are great for local transformations. If your callback becomes too complex, move it into a named function for readability and testability.