Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array_map function in php with parameter

Tags:

arrays

php

I have this

$ids = array_map(array($this, 'myarraymap'), $data['student_teacher']);  function myarraymap($item) {     return $item['user_id']; } 

I will would like to put an other parameter to my function to get something like

function myarraymap($item,$item2) {     return $item['$item2']; } 

Can someone can help me ? I tried lots of things but nothing work

like image 328
user1029834 Avatar asked Jan 05 '12 15:01

user1029834


People also ask

What is array_map function 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.

What exactly is the the difference between array_map Array_walk and Array_filter?

The resulting array of array_map has the same length as that of the largest input array; array_walk does not return an array but at the same time it cannot alter the number of elements of original array; array_filter picks only a subset of the elements of the array according to a filtering function.

What is array reduce in PHP?

Definition and Usage. The array_reduce() function sends the values in an array to a user-defined function, and returns a string. Note: If the array is empty and initial is not passed, this function returns NULL.


1 Answers

You can use an anonymous function and transmit value of local variable into your myarraymap second argument this way:

function myarraymap($item,$item2) {     return $item[$item2]; }  $param = 'some_value';  $ids = array_map(     function($item) use ($param) { return myarraymap($item, $param); },     $data['student_teacher'] ); 

Normally it may be enough to just pass value inside anonymous function body:

function($item) { return myarraymap($item, 'some_value'); } 
like image 59
Serge S. Avatar answered Oct 15 '22 03:10

Serge S.