Reputation: 37
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.
Upvotes: 1
Views: 42
Reputation: 227290
You can use array_map
to return you an array of just the elements you want.
For the 2nd example:
$thingsIActuallyWant = array_map(function($a){
return $a['id'];
}, $associativeList);
As for the 1st, I suggest using the foreach
as you have, because any alternative is going to be an ugly mess of array_map
and array_combine
.
Upvotes: 2
Reputation: 13614
You might try writing a function yourself, something like this:
function pluck($arr, $key)
{
$tbr = array();
foreach ($arr as $val)
{
if (is_array($val) && isset($val[$key]))
{
$tbr []= $val[$key];
}
elseif (is_object($val) && isset($val->$key))
{
$tbr [] = $val->$key;
}
}
return $tbr;
}
Then you could just call it:
$thingsIActuallyWant = pluck($associativeList, 'id');
Additionally, you should avoid passing variables by reference to foreach loops unless you need to.
Upvotes: 1