Oihana PHP

reduce.php

Table of Contents

Functions

reduce()  : array<string|int, mixed>
Reduces an array by removing values based on conditions or using compress/clean.

Functions

reduce()

Reduces an array by removing values based on conditions or using compress/clean.

reduce(array<string|int, mixed> $array[, bool|array<string|int, mixed>|callable $reduce = true ]) : array<string|int, mixed>

This function provides a unified interface for array reduction with three modes:

  • true: Remove null values using compress()
  • array: Forward options to compress()
  • callable: Custom filter function
Parameters
$array : array<string|int, mixed>

The input array.

$reduce : bool|array<string|int, mixed>|callable = true

Reduction mode:

  • true: compress with default options
  • array: compress with custom options
  • callable: fn($value, $key): bool
Tags
example

Remove nulls (default compress)

$data = ['a' => 1, 'b' => null, 'c' => 2];
$result = reduce($data, true);
// ['a' => 1, 'c' => 2]
example

Custom compress options

use oihana\core\options\CompressOption;

$data = ['a' => '', 'b' => null, 'c' => 'ok'];
$result = reduce( $data ,
[
    CompressOption::CONDITIONS =>
    [
        fn($v) => $v === null,
        fn($v) => $v === ''
    ]
]);
// ['c' => 'ok']
example

Custom callable

$data = ['name' => 'Alice', 'age' => 0, 'city' => 'Paris'];
$result = reduce($data, fn($v, $k) => is_string($v) && $v !== '');
// ['name' => 'Alice', 'city' => 'Paris']
example

Empty array

$result = reduce([], true);
// []
author

Marc Alcaraz

since
1.0.8
Return values
array<string|int, mixed>

The reduced array.


        
On this page

Search results