Array_map function in php with parameter
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
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'); }
PHP's array_map()
supports a third parameter which is an array representing the parameters to pass to the callback function. For example trimming the /
char from all array elements can be done like so:
$to_trim = array('/some/','/link');
$trimmed = array_map('trim',$to_trim,array_fill(0,count($to_trim),'/'));
Much easier than using custom functions, or other functions like array_walk()
, etc.
N.B. As pointed out in the comments below, I was a little hasty and the third param does indeed need to be same length as the second which is accomplished with array_fill()
.
The above outputs:
array(2) {
[0]=>
string(4) "some"
[1]=>
string(4) "link"
}
Consider using array_walk. It allows you to pass user_data
.