Php array map set keys
Here's my very simple, PHP 5.5-compatible solution:
The callable you supply should itself return an array with two values, i.e. Usage
Output
Partial applicationIn case you need to use the function many times with different arrays but the same mapping function, you can do something called partial function application (related to ‘currying’), which allows you to only pass in the data array upon invocation:
Which produces the same output, given NOTE: if your mapped function returns the same key for two different inputs, the value associated with the later key will win. Reverse the input array and output result of AlternativeFollowing is a variant of the above, which might prove more logical to some, but requires PHP 5.6:
In this variant, your supplied function (over which the data array is mapped) should instead return an associative array with one row, i.e.
If you are on PHP 5.3 to 5.5, the following is equivalent. It uses
UsageBoth of these variants would be used thus:
Note the The output is the same as before, and each can be partially applied in the same way as before. SummaryThe goal of the original question is to make the invocation of the call as simple as possible, at the expense of having a more complicated function that gets invoked; especially, to have the ability to pass the data array in as a single argument, without splitting the keys and values. Using the function supplied at the start of this answer:
Or, for this question only, we can make a simplification to
So the answer is NO, you can't avoid calling |