2

If I have an array structured like this:

$array[index]['first_name']
$array[index]['last_name']

Is there an easy way to implode it into something like first_name last_name,first_name last_name, etc. for all the indices?

Implode didn't seem to do what I wanted for something like this. Currently I'm just looping over the whole thing, but it's a SIGNIFICANT bottleneck.

2
  • How is the array getting set up? It may be more efficient to take care of it then instead of looping through the array later. Commented May 26, 2010 at 15:31
  • I don't have any control over how the array is set up, it's returned from a website's API Commented May 31, 2010 at 23:14

1 Answer 1

2
function combineFirstLastName($user) {
    return $user['first_name'] . ' ' . $user['last_name'];
}

$firstLastNames = array_map('combineFirstLastName', $array);

If you're using PHP >= 5.3, you can use an anonymous function.

$firstLastNames = array_map(function($user) {
    return $user['first_name'] . ' ' . $user['last_name'];
}, $array);

I'm not sure you'll get much more of a speed improvement, though. Have you considered opcode caching?

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

3 Comments

No, I haven't - I'm pretty new to PHP. Looking over the documentation briefly, it looks like you need to install it ahead of time on the server. Is that correct? I don't have root access - my webspace is provided through a hosting provider.
@Alex Zylman, Check phpinfo. You may have the extensions installed already.
@strabger, there's a lot of stuff listed in phpinfo and I'm not exactly sure where to look, but I scanned through the whole thing and nothing stood out. I also did a ctrl+f for apc with no luck.

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.