Array_map function in php with parameter

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'); }

As of PHP 7.4, you can use arrow functions (which are basically short anonymous functions with a briefer syntax) for more succinct code:

$ids = array_map(
    fn($item) => myarraymap($item, $param),
    $data['student_teacher']
);

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.


Apart from creating a mapper object, there isn't much you can do. For example:

class customMapper {
    private $customMap = NULL;
    public function __construct($customMap){
        $this->customMap = $customMap;
    }
    public function map($data){
        return $data[$this->customMap];
    }
}

And then inside your function, instead of creating your own mapper, use the new class:

$ids = array_map(array(new customMapper('param2'), 'map'), $data['student_teacher']);

This will allow you to create a custom mapper that can return any kind of information... And you can complexify your customMapper to accept more fields or configuration easily.

Tags:

Php

Arrays