For the following method
public function getSomeCollection(): array
{
// ...
return $collection;
}
we can return a mutated collection with only one element instead of N.
- return $collection;
+ return \count($collection) > 1 ? [array_keys($collection)[0] => array_values($collection)[0]] : $collection;
[array_keys($c)[0] => array_values($c)[0]]?Because array can be indexed by string keys, by IDs, so not just by indexes 0..N.
With such code
$collection = [33 => $userObject1, 44 => $userObject2];
[array_keys($collection)[0] => array_values($collection)[0]] will be evaluated to [33 => $userObject1];
and
$collection = ['abc'=> 1, 'def' => 2];
will be evaluated to ['abc'=> 1];
What do you think?
I think this could be a decent mutator, but it may be too complex of a mutation for it to make sense to users.
If i see the following diff, then i don't really know what is being mutated. So far, all diffs make it pretty clear what the 'new' behaviour of the code is.
- return $collection;
+ return \count($collection) > 1 ? [array_keys($collection)[0] => array_values($collection)[0]] : $collection;
So personally i'd say no to this mutator.
How about using array_slice() then?
array_slice() with preserve_keys=true should do the job, thank you @localheinz 馃憤
array_slice(['abc'=> 1, 'def' => 2], 0, 1, true) // ['abc' => 1]
array_slice([33 => $userObject1, 44 => $userObject2], 0, 1, true) // [33 => $userObject1]
So the diff will be:
- return $collection;
+ return \count($collection) > 1 ? array_slice($collection, 0, 1, true) : $collection;
Most helpful comment
array_slice()withpreserve_keys=trueshould do the job, thank you @localheinz 馃憤So the diff will be: