Array transformation question

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

If I have an array like: array(1=>"a",2=>"b",3=>"c")

What is the fastest way to turn it into:
array("a"=>"a","b"=>"b","c"=>"c") ?

I've looked at array_flip and some other native php functions, but
can't see a way to do it without manually looping over the array

Thanks for any suggestions.

Re: Array transformation question

Quoted text here. Click to load it

You could use array_walk, but why would you want to, since if the key
and value are always the same, you can just use the key and not bother
with the array at all???

Re: Array transformation question

Quoted text here. Click to load it

I'm using a framework that requires an array to build an html drop
down box. It constructs the options in the form of <option
value=3D"$key">$value</option>. I need the string that the user picks
from the list to be posted back, not the index of the array value they
picked. I figured transforming my data to fit the framework would be
easier than changing 3rd party code.

array walk invokes a callback for each element in the array, I can't
imagine that being faster than a foreach...

This is what I'm using for now:

     * Converts $array of (1=3D>"a",2=3D>"b",3=3D>"c") to
    public static function arrayToSet($array)
        foreach($array as $key => $value){
        return $new;

But don't like scripting things when there might be a native way...
Hence my original post.

Re: Array transformation question

El 09/02/2010 16:05, Mark Smith escribió/wrote:
Quoted text here. Click to load it

This seems to work, although you'd need to check for dupes and so on:


$foo = array(1=>"a",2=>"b",3=>"c");

$bar = array_combine(array_values($foo), array_values($foo));


-- - Álvaro G. Vicario - Burgos, Spain
-- Mi sitio sobre programación web:
-- Mi web de humor satinado:

Re: Array transformation question

On Feb 9, 3:15=A0pm, "=C1lvaro G. Vicario"
Quoted text here. Click to load it

Nice, thanks.

Site Timeline