Create array from array of keys and array of values

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
bernied
Forum Newbie
Posts: 2
Joined: Thu Nov 04, 2010 11:57 am
Location: Edinburgh, UK

Create array from array of keys and array of values

Post 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
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

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

Post by AbraCadaver »

array_combine()

Code: Select all

$fieldvalues = array_combine(array('Name1','Name2','NameEtc'), explode(',', $sometext));
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
bernied
Forum Newbie
Posts: 2
Joined: Thu Nov 04, 2010 11:57 am
Location: Edinburgh, UK

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

Post by bernied »

Ah yes, third down on the list of array functions, where I thought I'd already looked.
Thank you very much.
Post Reply