Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Basically, I have an array where each element is a key/value pair of elements, like this:

[myArray] => Array
        [0] => Array
                [id] => 121
                [name] => Value1
        [1] => Array
                [id] => 125
                [name] => Value2
        [2] => Array
                [id] => 129
                [name] => Value3
                ....

And I want to convert this to:

[myArray] => Array        
        [121] => Value1
        [125] => Value2
        [129] => Value3
        ....

so the 'id' element becomes the key, and the 'name' element becomes the value. Does PHP have something built in (or is there a clever trick) to do this? I'd like to avoid the obvious foreach() loop if there's something cleaner available...

share|improve this question
3  
I don't know if there is a built-in function to handle this task, but even if there is, it's definitely using some sort of loop structure to accomplish the task. A simple foreach loop should more than suffice. Is that a problem in your implementation? –  HartleySan Jul 17 '13 at 1:04
add comment

2 Answers

up vote 4 down vote accepted

PHP 5.5 has an array_column() function which can do this for you, if you're lucky enough to be running that already. The developer who submitted it also has a forwards-compatible version you can download for earlier versions of PHP.

However, it's pretty easy to roll your own, or just use a foreach loop for the particular case you need.

share|improve this answer
    
Unfortunately we're running in a 5.3 environment and that's not getting changed any time soon. Thanks though, array_column() is EXACTLY what I needed =) –  Malek Jul 17 '13 at 3:08
add comment

If you have array_column available you can do:

array_column($myArray, 'name', 'id')

I think the foreach is the much better option, though.

share|improve this answer
    
why the complicated combine? array_column($myArray, 'name','id') would suffice.. –  Ben Jul 17 '13 at 1:16
    
Ah. Wasn't aware of the index argument. Nice. –  Bill Criswell Jul 17 '13 at 1:21
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.