Oihana PHP

deleteKeyValue.php

Table of Contents

Functions

deleteKeyValue()  : array<string|int, mixed>|object
Deletes a value from an array or object using a dot-notated key path.

Functions

deleteKeyValue()

Deletes a value from an array or object using a dot-notated key path.

deleteKeyValue(array<string|int, mixed>|object $document, string $key[, string $separator = '.' ][, bool|null $isArray = null ]) : array<string|int, mixed>|object

This utility supports:

  • Flat keys (e.g., "name")
  • Nested keys (e.g., "user.profile.name")
  • Wildcard deletion for sub-containers (e.g., "user.*")
  • Global wildcard "*" to clear the entire document

The input can be an associative array or a stdClass-like object. Intermediate paths are ensured to exist before deletion.

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

The data source (array or object) to operate on.

$key : string

The key path to delete (e.g. "foo.bar" or "foo." or "").

$separator : string = '.'

The separator used to split the key path. Defaults to '.'.

$isArray : bool|null = null

Optional: force array (true) or object (false) mode; if null, auto-detects.

Tags
throws
InvalidArgumentException

If input is not array/object, if key is invalid, or if path traversal encounters a type mismatch.

author

Marc Alcaraz (ekameleon)

since
1.0.0
example

Delete an array key :

$doc = ['name' => 'Alice', 'age' => 30];
$doc = deleteKeyValue( $doc , 'age' ) ;
// Result: ['name' => 'Alice']

Delete an array complex key expression 'user.name" :

$doc = ['user' => ['name' => 'Alice', 'email' => 'a@b.c']];
$doc = deleteKeyValue($doc, 'user.name');
// Result: ['user' => ['email' => 'a@b.c']]

Deletes all object properties :

$doc = (object)['x' => 1, 'y' => 2];
$doc = deleteKeyValue($doc, '*');
// Result: (object)[]

Delete all properties with a wildcard key expression.

$doc = ['meta' => ['a' => 1, 'b' => 2]];
$doc = deleteKeyValue($doc, 'meta.*');
// Result: ['meta' => []]
example
$doc = (object)['user' => (object)['name' => 'Alice', 'email' => 'a@b.c']];
$doc = deleteKeyValue($doc, 'user.*');
// Result: (object)['user' => (object)[]]
Return values
array<string|int, mixed>|object

The updated document after deletion.


        
On this page

Search results