Skip to content

Commit a8cccac

Browse files
committed
Add parameter to method
1 parent 2e2ffb9 commit a8cccac

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

README.md

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -348,8 +348,13 @@ array(3) {
348348
}
349349
```
350350

351-
Though, if you want to keep array keys format to be same as class fields, you can pass false to `toArray` method:
352-
`$arr = $dto->toArray(false);` or `$arr = $dto->toArray(toSnakeCase: false);`
351+
`toArray` method accepts two parameters: `toSnakeCase` and `includeNulls`:
352+
353+
If you want to keep array keys format to be same as class fields, you can pass `toSnakeCase: false` parameter:
354+
`$arr = $dto->toArray(toSnakeCase: false);`
355+
356+
If you want to include keys with `null` values, you can pass `includeNulls: true` parameter:
357+
`$arr = $dto->toArray(includeNulls: true);`
353358

354359
The output then will be:
355360
```

src/ToArray.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,10 @@ trait ToArray
88

99
/**
1010
* @param bool $toSnakeCase
11+
* @param bool $includeNulls
1112
* @return array
1213
*/
13-
public function toArray(bool $toSnakeCase = true): array
14+
public function toArray(bool $toSnakeCase = true, bool $includeNulls = false): array
1415
{
1516
$arr = self::castToArray($this);
1617

@@ -22,7 +23,10 @@ public function toArray(bool $toSnakeCase = true): array
2223
{
2324
$key = ltrim(strtolower(preg_replace('/[A-Z]([A-Z](?![a-z]))*/', '_$0', $key)), '_');
2425

25-
$result[$key] = $value;
26+
if($value !== null || $includeNulls)
27+
{
28+
$result[$key] = $value;
29+
}
2630
}
2731

2832
return $result;

0 commit comments

Comments
 (0)