Array map php key value
Here's my very simple, PHP 5.5-compatible solution: Show
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 How to use array map PHP?PHP array_map() Function. Send each value of an array to a function, multiply each value by itself, and return an array with the new values: ... . Using a user-made function to change the values of an array: ... . Using two arrays: ... . Change all letters of the array values to uppercase: ... . Assign null as the function name:. What does array_ map return?array_map() returns an array containing the results of applying the callback to the corresponding value of array (and arrays if more arrays are provided) used as arguments for the callback. The number of parameters that the callback function accepts should match the number of arrays passed to array_map().
What is array_keys () used for in PHP?The array_keys() function returns an array containing the keys.
How array_ map works?The map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method. Generally map() method is used to iterate over an array and calling function on every element of array.
|