tags:

views:

43

answers:

2

Lets assume we have two PHP-Arrays:

 $some_array = array('a','b','c','d','e','f');
 $another_array = array(101,102,103,104,105,106);

In PHP, there are already some Array-Functions that allow the construction of an Associative Array (AKA hash), e,g,;

 $hash = array_combine(
           $some_array,
           $another_array
         );

And here it comes. What should I do if I want to create a hash in a more functional style, if I want to compute key and value on the fly and build the hash through a map-operation, like (not working):

 # wishful thinking
 $hash = array_map(
            function($a, $b){ return ($a => $b); },
            $some_array,
            $another_array
         );

The problem here seems to be the expectation, the line

            ...
            function($a, $b){ return ($a => $b); }
            ...

would indeed return an key value/pair of a hash - which it doesn't.

Q: How can I return a key/value pair from a function - which can be used to build up an associative array?

Thanks & regards

rbo


Addendum

To make clear what I really was looking for, I'll provide a perl example of hash generation:

 ...
 # we have one array of characters (on which our hash generation is based)

 my @array = qw{ a b c d e f };

 # now *generate* a hash with array contents as keys and 
 # ascii numbers as values in a *single operation *
 # (in Perl, the $_ variable represents the actual array element)

 my %hash = map +($_ => ord $_), @array;
 ...

Result (%hash):

 a => 97
 b => 98
 c => 99
 d => 100   
 e => 101
 f => 102

From the responses, I'd now think this is impossible in PHP. Thanks to all respondends.


+1  A: 

In PHP arrays can be associative too! An int-indexed array is just an associative array with 0 => element0 and so on. Thus, you can accomplish what you are looking for like this:

$somearray = array('name' => 'test', 'pass' => '***', 'group' => 'admin');

function myfunc($a, $b) { return array($a => $b); }

if($somearray['name'] == 'test') { echo 'it works!'; }

// Let's add more data with the function now
$somearray += myfunc('location', 'internet');

//Test the result
if($somearray['location'] == 'internet') { echo 'it works again!'; }

It is really very simple. Hope this helps.

hb2pencil
Hi hb2pencil, I tried to make a compact operation (like array_map) based on an array - which produces a list of key/value instances that make up the hash eventually. This is (as it looks now) impossible in PHP. I'll make an addendum to my posting in order to provide an "other-language"-example. Thanks!
rubber boots
+1  A: 
Helgi Hrafn Gunnarsson
Helgi, thank you very much for your comment. You say: "There is no way to return a single instance of a key/value pair in PHP". This is what I already suspected. So I know that from now on ;-) Thanks.
rubber boots
i think my comment summarized what he said here... :) nvm
ultrajohn