1

I've recently been using array_map to replace this kind of code:

$users = ...;
$usersIds = array();
foreach ($users as $user) {
   $usersIds[] = $user->getId();
}

with

$users = ...;
$usersIds = array_map(function ($user) {
    return $user->getId();
}, $users);

It's more elegant, and i guess that this more efficient.

Now i'd like to know if the following code could be improved with a function similar to array_map:

$users = ...;
$indexedUsers = array();
foreach ($users as $user) {
    $indexedUsers[$user->getId()] = $user;
}

3 Answers 3

3

As you already have the keys, just combine it:

$indexedUsers = array_combine($usersIds, $users);

Apart from that, foreach normally is elegant, especially these trivial cases you outline don't need much function logic, so I'd prefer the iterator pattern here instead of going functional.

Sign up to request clarification or add additional context in comments.

1 Comment

I generally agree, so +1. There shouldn't be (much) performance gain / loss unless there is some more logic involved.
2

First off, I doubt array_map() is faster than your original foreach loop. Never change code because you think it's faster. Of course, if you think it's more elegant and the speed difference is insignificant, then nobody should care.

You can often think of using iterators in these contexts:

class ArrayGetIdIterator extends ArrayIterator
{
  public function key()
  {
    return $this->current()->getId();
  }
}

$indexedUsers = iterator_to_array(new ArrayGetIdIterator($users));

To minimize boilerplate code and maximize reusability, the constructor could accept some type of arguments (e.g, which function to call) and you could create a static helper.

Although, personally, I would just take your original code, wrap it into a reusable function and call it a day.

Comments

1

You can build on your former success and use array_combine...

$get_user_id = function($user) {return $user->getId();};
$indexedUsers = array_combine(array_map($get_user_id, $users), $users);

3 Comments

array_walk returns a boolean, and array_combine expects the first argument to be an array. Your code does not work.
My apologies, that's a typo; it was meant to mirror your code and be array_map...
As evident in the order of parameters :-) Change has been made.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.