Skip to content

Commit ac938e3

Browse files
committed
Added renameKeys method
1 parent cbcbeb4 commit ac938e3

File tree

3 files changed

+74
-0
lines changed

3 files changed

+74
-0
lines changed

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1212
- `Fixed` for any bug fixes.
1313
- `Security` in case of vulnerabilities
1414

15+
## [1.1.0] - 2020.11.23
16+
17+
### Added
18+
19+
- Added `renameKeys` method.
20+
1521
## [1.0.1] - 2020.08.02
1622

1723
### Changed

README.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ composer require bayfrontmedia/php-array-helpers
4040
- [missing](#missing)
4141
- [isMissing](#ismissing)
4242
- [multisort](#multisort)
43+
- [renameKeys](#renamekeys)
4344
- [query](#query)
4445

4546
<hr />
@@ -450,6 +451,41 @@ $sorted = Arr::multisort($clients, 'first_name');
450451

451452
<hr />
452453

454+
### renameKeys
455+
456+
**Description:**
457+
458+
Rename array keys while preserving their order.
459+
460+
**Parameters:**
461+
462+
- `$array` (array): Original array
463+
- `$keys` (array): Key/value pairs to rename
464+
465+
**Returns:**
466+
467+
- (array)
468+
469+
**Example:**
470+
471+
```
472+
use Bayfront\ArrayHelpers\Arr;
473+
474+
$user = [
475+
'UserID' => 5,
476+
'UserEmail' => '[email protected]',
477+
'UserGroup' => 'Administrator'
478+
];
479+
480+
$renamed = Arr::renameKeys($user, [
481+
'UserID' => 'id',
482+
'UserEmail' => 'email',
483+
'UserGroup' => 'group'
484+
]);
485+
```
486+
487+
<hr />
488+
453489
### query
454490

455491
**Description:**

src/Arr.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,38 @@ public static function multisort(array $array, string $key, bool $descending = f
326326

327327
}
328328

329+
/**
330+
* Rename array keys while preserving their order.
331+
*
332+
* @param array $array (Original array)
333+
* @param array $keys (Key/value pairs to rename)
334+
*
335+
* @return array
336+
*/
337+
338+
public static function renameKeys(array $array, array $keys): array
339+
{
340+
341+
$new_array = [];
342+
343+
foreach ($array as $k => $v) {
344+
345+
if (array_key_exists($k, $keys)) {
346+
347+
$new_array[$keys[$k]] = $v;
348+
349+
} else {
350+
351+
$new_array[$k] = $v;
352+
353+
}
354+
355+
}
356+
357+
return $new_array;
358+
359+
}
360+
329361
/**
330362
* Convert array into a query string
331363
*

0 commit comments

Comments
 (0)