Oihana PHP

compress.php

Table of Contents

Functions

compress()  : array<string|int, mixed>
Compresses the given array by removing values that match one or more conditions.

Functions

compress()

Compresses the given array by removing values that match one or more conditions.

compress(array<string|int, mixed> $array[, array<string|int, mixed>|null $options = [] ][, int $currentDepth = 0 ]) : array<string|int, mixed>

Useful for cleaning up associative arrays (e.g., from form submissions or object exports) by removing nulls, empty strings, or other unwanted values. Supports recursion into nested arrays or objects.

Parameters
$array : array<string|int, mixed>

The input array to compress.

$options : array<string|int, mixed>|null = []

Optional configuration:

  • clone (bool) If true, works on a cloned copy of the array. Original remains unchanged. (default: false)
  • conditions (callable|array) One or more callbacks: (mixed $value): bool. If any condition returns true, the value is removed. ( default: fn($v) => is_null($v) )*
  • excludes (string[]) List of keys to exclude from filtering, even if matched by a condition.
  • recursive (bool) Whether to recursively compress nested arrays or objects. (default: true)
  • depth (int|null) Maximum depth for recursion. null means no limit.
  • throwable (bool) If true, throws InvalidArgumentException for invalid conditions. (default: true)
$currentDepth : int = 0

(Internal) Tracks current recursion depth. You usually don’t need to set this.

Tags
example

Basic cleanup of null values

use function oihana\core\arrays\compress;
$data = ['id' => 1, 'name' => 'hello', 'description' => null];
$clean = compress($data);
// Result: ['id' => 1, 'name' => 'hello']

Exclude a specific key from filtering

$data = ['id' => 1, 'name' => null];
$clean = compress($data, ['excludes' => ['name']]);
// Result: ['id' => 1, 'name' => null]  // "name" is preserved

Remove null or empty strings

$conditions =
[
    fn($v) => is_null($v),
    fn($v) => is_string($v) && $v === ''
];
$data  = ['a' => '', 'b' => 0, 'c' => null];
$clean = compress($data, ['conditions' => $conditions]);
// Result: ['b' => 0]

Recursive compression with depth limit

$nested =
[
    'id'   => 2,
    'meta' => ['created' => null, 'tags' => []],
];

$clean = compress($nested,
[
    'conditions' => fn($v) => $v === [] || $v === null,
    'depth'      => 1
]);
// Result: ['id' => 2]

Clone input before compressing

$original = ['x' => null, 'y' => 5];
$copy     = compress($original, ['clone' => true]);
// $original remains unchanged; $copy == ['y' => 5]
author

Marc Alcaraz (ekameleon)

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

The compressed array (or its clone if clone=true).


        
On this page

Search results