Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Can I get the index in an array_map function?

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?

like image 201
Ollie Glass Avatar asked May 03 '11 11:05

Ollie Glass


People also ask

How do you get the value of a particular index of an array in PHP?

We can get the array index by using the array_search() function. This function is used to search for the given element.

What is the use of array_map in PHP?

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.

How do you check if an index exists in PHP?

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.


1 Answers

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); 
like image 182
Aron Rotteveel Avatar answered Sep 18 '22 21:09

Aron Rotteveel