49

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

4
  • What do you want $item2 to be? A constant value? Commented Jan 5, 2012 at 15:58
  • 1
    I think your call to array_map is flawed. Could you provide a proper example? Commented Jan 5, 2012 at 16:01
  • array_map : The number of parameters that the callback function accepts should match the number of arrays passed to the array_map() Trick : You can use a array as param holder e.g. array array_map ( callable $callback, array_to_map,array('param') ) Commented May 7, 2014 at 9:01
  • Your snippet is the perfect demonstration of how to obscure your code by avoiding native PHP functions. The simpler solution is to not re-invent array_column(). 3v4l.org/ZQXPo See Is there a function to extract a 'column' from an array in PHP? Commented Aug 29, 2023 at 2:25

5 Answers 5

64

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']
);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for highlighting the use of arrow functions here. It's nice that variables in the parent scope are automatically included rather than needing use($param)
44

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

5 Comments

It doesn't seem to work the way you described. Test it. The third parameter needs to be an array of elements - each of these elements is passed as an argument together with the matching element from the array being trimmed: $trimmed = array_map('trim',array('/some/','/link'),array('/', '/'));
@cascaval I had corrected on my own end after noticing the same and forgot to come back to post update. Thanks for the heads up, please see the updated answer, and if useful, please re-vote ;)
What does "N.B." mean?
@elbowlobstercowstand "nota bene" or take note / note well... It's Latin en.m.wikipedia.org/wiki/Nota_bene
As useful as this is, I have to say the way the PHP devs have implemented this third param here is a bit absurd since it almost always requires the extremely awkward array_fill(0,count($to_trim), 'my params')
10

Consider using array_walk. It allows you to pass user_data.

1 Comment

But how can we pass parameters if more than one argument?
5

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.

Comments

2

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

<?php

function myFunc($item, $param) {
    echo $param . PHP_EOL;
}

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

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

// the foo param
// the bar 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."

2 Comments

Maybe test the code you posted? The output will be 'foo' then 'bar'. If you added a second parameter to myFunc, it would be passed 'the param' only for the first element of $array. For subsequent elements it would be passed null because “if the arrays are of unequal length, shorter ones will be extended with empty elements to match the length of the longest.”
Thank your for pointing out the error. I just updated my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.