phparrayslaravelhelper

How to rename key of array with Arr::only helper?


I'm using Arr::only to fetch values from an array by their key, however I need to rename the ShortDesc key to use snake case not camel case. Is this possible with Arr::only or do I need to use an array_map?

Here's my brilliant code.

$myArray = Arr::only($targetArray, ["title", "shortDesc"]);

Solution

  • You could possibly use collections for this instead of the helper methods:

    $array = [
        'title'          => 'The title',
        'shortDesc'      => 'The short description',
        'someOtherValue' => 'foobar',
    ];
    
    $newArray = collect($array)
        ->only('title', 'shortDesc')
        ->keyBy(function ($item, $key) {
            return Str::snake($key);
        })->toArray();