I'm using a map in php like so:
function func($v) { return $v * 2; } $values = array(4, 6, 3); $mapped = array_map(func, $values); var_dump($mapped);
Is it possible to get the index of the value in the function?
Also - if I'm writing code that needs the index, should I be using a for loop instead of a map?
We can get the array index by using the array_search() function. This function is used to search for the given element.
The array_map() is an inbuilt function in PHP and it helps to modify all elements one or more arrays according to some user-defined condition in an easy manner. It basically, sends each of the elements of an array to a user-defined function and returns an array with new values as modified by that function.
The array_key_exists() is an inbuilt function of PHP that is used to check whether a specific key or index is present inside an array or not. The function returns true if the specified key is found in the array otherwise returns false.
Sure you can, with the help of array_keys():
function func($v, $k) { // key is now $k return $v * 2; } $values = array(4, 6, 3); $mapped = array_map('func', $values, array_keys($values)); var_dump($mapped);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With