TheWebs
TheWebs

Reputation: 12923

Creating an associative array from an array, based on the array - PHP

I have a unique issue that I have never heard of this being possible to do before:

So essentially I have a function that takes in a an array of arguments such as:

function someFunction(array $arguments){}

and gives me an array back as such:

array('option1', 'option2', 'options3', ...);

I then need to take that array and loop through it creating an associative array such as:

array('option1' => call_come_method('option1'), .... );

heres the kicker, you will never know how many arguments a user passes into the function, yet each one needs to created into a key=>value arrangement as seen above.

Now i did some research and I was told the $argv command in php, how ever where I am stumped is how to implement it in this case.

So if any one can give me any pointers I would be appreciative.

Upvotes: 0

Views: 49

Answers (2)

gen_Eric
gen_Eric

Reputation: 227190

This is a lot easier than you think. First use array_flip to switch the array's keys and values.

$newArray = array_flip($arguments);

Then loop though it and call the method:

foreach($newArray as $key=>&$val){
    $val = call_come_method($key);
}

The &, makes it a reference, so the array value is updated.

DEMO: http://codepad.org/giL1KPA3

UPDATE: You don't even need array_flip, you just need a for loop.

$newArray = array();
foreach($arguments as $val){
    $newArray[$val] = call_come_method($val);
}

DEMO: http://codepad.org/AQ1gWrou

Upvotes: 2

moonwave99
moonwave99

Reputation: 22817

you will never know how many arguments a user passes into the function

FYI, you get to know it with func_get_args().

This way you don't need to provide your function with an $arguments parameter, but you just leave it empty.

Upvotes: 1

Related Questions