From 48147745f5fe4378b3fb3175078f9009f71872bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A9sz=C3=A1ros=20Lajos?= Date: Sun, 25 Jul 2021 02:26:52 +0200 Subject: [PATCH] Added associative array support for O::assoc and O::dissoc --- README.md | 23 +++++++++++++++++++++++ src/O.php | 16 ++++++++++++---- 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index f00443a..a95807d 100644 --- a/README.md +++ b/README.md @@ -881,6 +881,17 @@ $point2d->y = 20; $point3d = O::assoc("z", 30, $point2d); // {"x": 10, "y": 20, "z": 30} ``` +```php +$point2d = [ + "x" => 10, + "y" => 20 +]; + +$point3d = O::assoc("z", 30, $point2d); // ["x" => 10, "y" => 20, "z" => 30] +``` + +**Does not work on arrays with numeric keys!** +
@@ -897,6 +908,18 @@ $point3d->z = 30; $point2d = O::dissoc("z", 30, $point3d); // {"x": 10, "y": 20} ``` +```php +$point3d = [ + "x" => 10, + "y" => 20, + "z" => 30 +]; + +$point2d = O::dissoc("z", 30, $point3d); // ["x" => 10, "y" => 30] +``` + +**Does not work on arrays with numeric keys!** +
diff --git a/src/O.php b/src/O.php index 8315510..611aedc 100644 --- a/src/O.php +++ b/src/O.php @@ -45,14 +45,22 @@ function ($result, $key) use ($data) { } // O::assoc('foo', 'bar', {}) -> {foo: 'bar'} - public static function assoc(string $key, $value, object $data): object { - $data->{$key} = $value; + public static function assoc(string $key, $value, $data): object { + if (O::isObject($data)) { + $data->{$key} = $value; + } elseif(A::isArray($data) && A::isAssoc($data)) { + $data[$key] = $value; + } return $data; } // O::dissoc('foo', {foo: 'bar', fizz: 'buzz'}) -> {fizz: 'buzz'} - public static function dissoc(string $key, object $data): object { - unset($data->{$key}); + public static function dissoc(string $key, $data): object { + if (O::isObject($data)) { + unset($data->{$key}); + } elseif(A::isArray($data) && A::isAssoc($data)) { + unset($data[$key]); + } return $data; }