Page 1 of 1

Create array from array of keys and array of values

Posted: Thu Nov 04, 2010 12:12 pm
by bernied
Hi,

This is my first post, and I'm fairly new at php, so please be gentle.

I'm trying to find out how to make an array from an array of keys and an array of values. The array of values is returned from the explode function, so has numeric keys, but I want these to be named/associative. I feel that there should be a function for this, but can only do it with a messy for loop.

Code: Select all

                    $fieldnames = array('Name1','Name2','NameEtc');
                    $fieldvalues = explode(',', $sometext);
# this is the bit I want a function for, like:
#                   $line = somefunction($fieldnames,$fieldvalues);
# but instead, I have to do this:
                    for ($j=0; $j < count($fieldnames); $j++) {
                        $line[$fieldnames[$j]] = $fieldvalues[$j];
                    }
Even better would be a function that just changes the keys in $fieldvalues to the contents of $fieldnames, so no need for $lines array.

php seems so concise and neat, I find it hard to believe this function doesn't exist

I hope this makes sense.
Bernie

Re: Create array from array of keys and array of values

Posted: Thu Nov 04, 2010 12:14 pm
by AbraCadaver
array_combine()

Code: Select all

$fieldvalues = array_combine(array('Name1','Name2','NameEtc'), explode(',', $sometext));

Re: Create array from array of keys and array of values

Posted: Thu Nov 04, 2010 5:19 pm
by bernied
Ah yes, third down on the list of array functions, where I thought I'd already looked.
Thank you very much.