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; }