I often run into this situation:
foreach ($someObjects as &$someObject)
{
$someObjectsIndex[$someObject->id] = $someObject;
}
And this:
$thingsIActuallyWant = [];
foreach ($associativeList as &$associativeItem)
{
$thingsIActuallyWant[] = $associativeItem['id'];
}
I was wondering if there is an existing method or something to write these things shorter, without writing the foreach loop.
You can use
array_mapto return you an array of just the elements you want.For the 2nd example:
As for the 1st, I suggest using the
foreachas you have, because any alternative is going to be an ugly mess ofarray_mapandarray_combine.