Home » Php » arrays – Array_map function in php with parameter

arrays – Array_map function in php with parameter

Posted by: admin April 23, 2020 Leave a comment

Questions:

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

How to&Answers:

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.

Answer:

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

Answer:

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"
}

Answer:

Consider using array_walk. It allows you to pass user_data.

Answer:

Consider using the third parameter from array_map function to pass additional parameter to callable function. Example:

<?php

function myFunc($param) {
    echo $param;
}

$array = ['foo', 'bar'];

array_map('myFunc', $array, ['the param']);

// the param
// the param

Ref: https://www.php.net/manual/en/function.array-map.php

The docs said about the third param from array_map function: “Supplementary variable list of array arguments to run through the callback function.”